1786 数据流中的算法 - 众数 STL/ 线段树 水题

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|1
using 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);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值