线段树?分块大法好


1 #include <bits/stdc++.h> 2 using namespace std; 3 typedef long long ll; 4 //#define ll int 5 const int N = 2e5 + 10; 6 7 int n, m, a[N]; 8 9 int L[N], R[N], bel[N], len, cnt; 10 11 int p[500]; 12 13 ll sum[450], tag[450], vl[N], dat[N][450]; 14 15 void sol(int pos, int val) { 16 17 } 18 19 inline int query() { 20 for(int i = 1 ; i <= cnt ; ++ i) { 21 ll val = -tag[i]; 22 if(dat[i][1] <= val && val <= dat[i][p[i]]) { 23 ll fn = *lower_bound(dat[i] + 1, dat[i] + 1 + p[i], val); 24 if(fn == val) { 25 for(int j = L[i] ; j <= R[i] ; ++ j) { 26 if(vl[j] == val) { 27 return j; 28 } 29 } 30 } 31 } 32 } 33 return -1; 34 } 35 36 struct FastIO { 37 static const int S = 1e7; 38 int wpos; 39 char wbuf[S]; 40 FastIO() : wpos(0) {} 41 inline int xchar() { 42 static char buf[S]; 43 static int len = 0, pos = 0; 44 if (pos == len) 45 pos = 0, len = fread(buf, 1, S, stdin); 46 if (pos == len) exit(0); 47 return buf[pos++]; 48 } 49 inline int xuint() { 50 int c = xchar(), x = 0; 51 while (c <= 32) c = xchar(); 52 for (; '0' <= c && c <= '9'; c = xchar()) x = x * 10 + c - '0'; 53 return x; 54 } 55 ~FastIO() 56 { 57 if (wpos) fwrite(wbuf, 1, wpos, stdout), wpos = 0; 58 } 59 } io; 60 61 template<typename T> void read(T &x) { 62 char c = x = 0; 63 while(!isdigit(c)) c = getchar(); 64 while(isdigit(c)) x = x * 10 + c - '0', c = getchar(); 65 } 66 67 int main() { 68 n = io.xuint(), m = io.xuint(); 69 len = min(n, int(sqrt(n)) + 1); 70 cnt = (n - 1) / len + 1; 71 ll s = 0; 72 for(int i = 1 ; i <= n ; ++ i) { 73 int id = (i - 1) / len + 1; 74 if(!L[id]) L[id] = i; R[id] = i; 75 bel[i] = id, a[i] = io.xuint(); 76 dat[id][++ p[id]] = s - a[i]; 77 vl[i] = s - a[i]; 78 sum[id] += a[i]; 79 s += a[i]; 80 } 81 for(int i = 1 ; i <= cnt ; ++ i) { 82 sort(dat[i] + 1, dat[i] + 1 + p[i]); 83 sum[i] += sum[i - 1]; 84 } 85 for(int i = 1, pos, val ; i <= m ; ++ i) { 86 pos = io.xuint(), val = io.xuint(); 87 88 val = val - a[pos]; 89 if(val) { 90 a[pos] += val; 91 int id = bel[pos]; 92 p[id] = 0; 93 ll s = sum[id - 1]; 94 95 for(int i = L[id] ; i <= R[id]; ++ i) { 96 dat[id][++ p[id]] = s - a[i]; 97 vl[i] = s - a[i]; 98 s += a[i]; 99 } 100 101 sort(dat[id] + 1, dat[id] + 1 + p[id]); 102 103 tag[id] = 0; 104 105 sum[id] += val; 106 for(int i = id + 1 ; i <= cnt ; ++ i) { 107 sum[i] += val; 108 tag[i] += val; 109 } 110 } 111 printf("%d\n", query()); 112 } 113 }