Codeforces 818D Multicolored Car(思维+线段树)

题意:

现在有N辆车经过,A和B玩一个游戏,他们统计他们自己喜欢的颜色的车辆的个数。

一开始对手已经选好了颜色A.我们现在要选择一个颜色,使得Cnti(chose)>=Cnti(A);

这里Cnti()表示到位子i,该颜色出现的车辆个数。

如果存在多解,输出任意一个可行解即可。


思路:

 

考虑当前数的贡献:

如果当前数字是A,那么对其他所有数来说,都需要有一个数才能满足,否则这个数直接pass。

因此可以出现A,让其他所有数都-1,如果此时是负数了,那就彻底gg。

然后出现不是A的其他数字,其贡献就是给本身这个次数+1。不过要先判他是不是已经gg了。不gg还能加1,gg了就让他保持负数。

因此构造出一颗线段树,记录每一种颜色都出现了多少次。

遍历这N辆车,当前是A,我们对应在这棵树中所有位子都减1.表示需要其他位子需要有一个数来抵消这个cnt(A);

如果当前!=A,如果此时这个位子不是负数(即之前所有位子都没有出现过A颜色的车辆多于这种颜色的车辆的情况),那么对应这种颜色就可能是一个可行解,那么对应modify(i,i,1);

最终在1e6种颜色,也就是1e6个位置上,找到一个>=0的任意一个颜色就是答案。

 


#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=1e6+100;
typedef long long LL;
struct Tree{
    LL l,r,maxval,minval,sum,tag;///区间最大值,区间最小值,区间和,l
}tree[maxn*4];
void push_up(LL p)
{
    tree[p].maxval=max(tree[p*2].maxval,tree[p*2+1].maxval);
    tree[p].minval=min(tree[p*2].minval,tree[p*2+1].minval);
    tree[p].sum=tree[p*2].sum+tree[p*2+1].sum;
}
void addtag(LL p,LL d)
{
    tree[p].tag+=d;
    tree[p].sum+=d*(tree[p].r-tree[p].l+1);
    tree[p].maxval=tree[p].tag;
    tree[p].minval=tree[p].tag;
}
void push_down(LL p)
{
    if(tree[p].tag!=0){
        addtag(p*2,tree[p].tag);
        addtag(p*2+1,tree[p].tag);
        tree[p].tag=0;
    }
}
void build(LL p,LL l,LL r)
{
    tree[p].l=l;tree[p].r=r;tree[p].maxval=-1e18;tree[p].minval=1e18;
    tree[p].sum=0;tree[p].tag=0;
    if(l==r) {tree[p].maxval=tree[p].minval=tree[p].sum=0;return;}
    LL mid=(l+r)>>1;
    build(p*2,l,mid);
    build(p*2+1,mid+1,r);
    push_up(p);
}
void modify(LL p,LL l,LL r,LL d)
{
    if(l<=tree[p].l&&r>=tree[p].r)///要修改的区间涵盖在区间内部
    {
            addtag(p,d);
            return;
    }
    push_down(p);
    LL mid=(tree[p].l+tree[p].r)>>1;
    if(l<=mid) modify(p*2,l,r,d);
    if(r>mid) modify(p*2+1,l,r,d);
    push_up(p);
}
LL query(LL p,LL l,LL r)
{
    if(l<=tree[p].l&&r>=tree[p].r)
    {
            return tree[p].sum;
    }
    LL ans=0;
    push_down(p);
    LL mid=(tree[p].l+tree[p].r)>>1;
    if(l<=mid) ans+=query(p*2,l,r);
    if(r>mid) ans+=query(p*2+1,l,r);
    return ans;
}
int main(void)
{
  cin.tie(0);std::ios::sync_with_stdio(false);
  LL n,b;cin>>n>>b;
  build(1,1,1000000);
  for(LL i=1;i<=n;i++){
    LL x;cin>>x;
    if(x==b){
        modify(1,1,1000000,-1);
    }
    else{
        if(query(1,x,x)>=0){
            modify(1,x,x,1);
        }
    }
  }
  LL ans=-1;
  for(LL i=1;i<=1000000;i++){
     if(i==b) continue;
     if(query(1,i,i)>=0){
        ans=i;
        break;
     }
  }
  cout<<ans<<"\n";
return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值