[树状数组][二分]JZOJ 5871 挑战

Description

 

Input

Output

 

Sample Input

10 7
0 3 1 4 6 2 7 8 10 1
2 5
1 3
9 36
4 10
4 9
1 2
1 0

Sample Output

1
-1
9
-1
4
-1
1
 

Data Constraint

分析

树状数组二分微调一下就行

 

#include <iostream> 
#include <cstdio>
#define lowbit(x) x&-x
using namespace std;
typedef long long ll;
const int N=2e5+10;
ll t[N],a[N];
int n,m;

void Plus(int x,ll delta) {
    for (int i=x;i<=n;i+=lowbit(i)) t[i]+=delta;
}

ll Query(int x) {
    ll ans=0;
    for (int i=x;i;i-=lowbit(i)) ans+=t[i];
    return ans;
}

int Bin_Search(int x) {
    int ans=n+1,l=x+1,r=n;
    ll sum=Query(x);
    while(l<=r) {
        int mid=l+r>>1;
        if (Query(mid)>=sum*2ll) r=mid-1,ans=mid; else l=mid+1;
    }
    return ans;
}

int main() {
    freopen("challenge.in","r",stdin);
    freopen("challenge.out","w",stdout);
    scanf("%d%d",&n,&m);
    ll sum=0;
    int ans=n+1;
    for(int i=1;i<=n;i++) {
        scanf("%lld",&a[i]);
        Plus(i,a[i]);
        if (ans>n&&sum==a[i]) ans=i;
        sum+=a[i];
    }
    for (int i=1;i<=m;i++) {
        int x;
        ll y;
        scanf("%d%lld",&x,&y);
        Plus(x,y-a[x]);a[x]=y;
        if(x>ans) {
            printf("%d\n",ans);
            continue;
        }
        ans=n+1;
        if (Query(x-1)*2ll==Query(x)) ans=x;
        else 
        while (x<=n) {
            int now=Bin_Search(x);
            if (!now) break;
            if (Query(now-1)*2ll==Query(now)) {
                ans=now;
                break;
            }
            x=now;
        }
        printf("%d\n",ans>n?-1:ans);
    }
    fclose(stdin);fclose(stdout);
}
View Code

 

posted @ 2018-09-21 21:58  Vagari  阅读(171)  评论(0编辑  收藏  举报