Educational Codeforces Round 87 D- Multiset(树状数组+二分)

Educational Codeforces Round 87 D- Multiset(树状数组+二分)_第1张图片

题意:给你长度为n的数组,q次询问若给出是询问k>0则添加k这个数到数组里,反之则删除第 |k| 个数。最后输出数组剩下的任意一个数,没有输出0;

思路:用树状数组的下标存储数组中的数和其出现次数,当k大于0直接添加进入树状数组里,若小于0,则二分查询其在树状数组对应的下标将其修改为0(删除)。

#include 
#include 
#include 
#include 
//#include
using namespace std;
typedef long long ll;
#define space putchar(' ')
#define enter putchar('\n')
typedef pair<int,int> PII;
const int inf=0x3f3f3f3f;
const int mod=1e9+7;
const int N=2e6+10;
const double esp=1e-10;


ll gcd(ll a,ll b)
{
    return b==0?a:gcd(b,a%b);
}

ll lcm(ll a,ll b)
{
    return a*(b/gcd(a,b));
}

template <class T>
void read(T &x)
{
    char c;
    bool op = 0;
    while(c = getchar(), c < '0' || c > '9')
        if(c == '-')
            op = 1;
    x = c - '0';
    while(c = getchar(), c >= '0' && c <= '9')
        x = x * 10 + c - '0';
    if(op)
        x = -x;
}
template <class T>
void write(T x)
{
    if(x < 0)
        x = -x, putchar('-');
    if(x >= 10)
        write(x / 10);
    putchar('0' + x % 10);
}
int a[N];
int n,m;
int lowbit(int x)
 {
     return x&(-x);
 }
 void update(int x,int y)
 {

     while(x<=n)
     {
         a[x]+=y;
         x+=lowbit(x);
     }

 }
int query(int x)
 {
     int ans=0;

     while(x>0)
     {
         ans+=a[x];
         x-=lowbit(x);
     }
     return ans;
 }
 int fnd(int x)
 {
     int l=0,r=n,ans;
     while(l<=r)
     {
         int mid=(l+r)/2;
         if(x<=query(mid)){
                ans=mid;
                r=mid-1;
         }
         else l=mid+1;
     }
     return ans;
 }


int main()
{
    read(n),read(m);
    for(int i=1;i<=n;i++)
    {
        int x;
        read(x);
        update(x,1);

    }
    while(m--)
    {
        int x;
        read(x);
        if(x>0)
        {
            update(x,1);
        }
        else
        {
         update(fnd(-x),-1);
        }
    }
    for(int i=1;i<=n;i++)
        if(a[i]>0)
    {
        printf("%d\n",i);return 0;
    }
    printf("0\n");





    return 0;
}






你可能感兴趣的:(CF)