1786 数据流中的算法

来源:互联网 发布:2016年淘宝用户人数 编辑:程序博客网 时间:2024/05/21 11:10

http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1786

挺水的一道题,看网上题解是map加set过的。
我用线段树水了过去。
用map哈希一下每个用户的id,以哈希值为下标,访问次数为值,用线段树维护最大值和最大值所对应的最小id。 复杂度O(nlogn)
其实用线段树感觉不太行。
一共有5*1e6组询问 如果全是操作1,那么线段树是存不下的。
虽然理论上不太行,但是数据水呀QAQ。
我只开了1e6的数组就水过去了。

#include<cstdio>#include<cstdlib>#include<cstring>#include<cmath>#include<iostream>#include<algorithm>#include<map>#include<deque>#include<queue>#include<bitset>#include<vector>#define lson l,m,rt<<1#define rson m+1,r,rt<<1|1using namespace std;const int MAX=1e6+10;int sum[MAX<<2];int a[MAX<<2];void push_up(int rt){    if(sum[rt<<1]>sum[rt<<1|1])        a[rt]=a[rt<<1];    else if(sum[rt<<1]<sum[rt<<1|1])        a[rt]=a[rt<<1|1];    else        a[rt]=min(a[rt<<1],a[rt<<1|1]);    sum[rt]=max(sum[rt<<1],sum[rt<<1|1]);}void build(int l,int r,int rt){    if(l==r)    {        sum[rt]==0;        return;    }    int m=(l+r)>>1;    build(lson);    build(rson);    push_up(rt);}void update(int name,int c,int p,int l,int r,int rt){    if(l==r)    {        sum[rt]+=c;        a[rt]=name;        return;    }    int m=(l+r)>>1;    if(m>=p) update(name,c,p,lson);    if(m<p) update(name,c,p,rson);    push_up(rt);}void print(int l,int r,int rt){    if(l==r)    {        cout<<a[rt]<<" ";        return ;    }    int m=(l+r)>>1;    print(lson);    print(rson);}int read()  {      int x=0,f=1;char ch=getchar();      while(ch<'0' || ch>'9') {if(ch=='-') f=-1;ch=getchar();}      while(ch>='0' && ch<='9') {x=x*10+ch-'0';ch=getchar();}      return x*f;  } int main(){    int tot=0;    map<int,int> M;    queue<int> Q;    int n,k;    scanf("%d %d",&n,&k);    int sizes=0;int op=0;    int cnt;    for(int i=0;i<n;i++)    {        op=read();        if(op==2)        {            printf("%d\n",a[1]);            //cout<<"fuck"<<sum[1]<<endl;        }        else        {            cnt=read();            if(M.count(cnt)==0)                M[cnt]=++tot;            Q.push(cnt);            if(sizes>=k)            {                update(Q.front(),-1,M[Q.front()],1,n,1);                Q.pop();            }            else                sizes++;            update(cnt,1,M[cnt],1,n,1);        }    }}
原创粉丝点击