1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
| #include <bits/stdc++.h> using namespace std; const int Maxn=2e5+5; int n,q; int X[Maxn]; int Tree[Maxn<<2]; void spread(int p) { if(Tree[p]) { Tree[p<<1]=Tree[p<<1|1]=Tree[p]; Tree[p]=0; } } void build(int p,int l,int r) { if(l==r) { Tree[p]=l; return ; } int mid=(l+r)>>1; build(p<<1,l,mid); build(p<<1|1,mid+1,r); } int ask_num(int p,int l,int r,int x) { if(l==r) { return Tree[p]; } int mid=(l+r)>>1; spread(p); if(x<=mid) { return ask_num(p<<1,l,mid,x); } else { return ask_num(p<<1|1,mid+1,r,x); } }
int get_pos(int x) { int res = ask_num(1,1,n,x); return X[res]+(x-res); }
void update(int p,int l,int r,int L,int R,int x) { if(L<=l&&r<=R) { Tree[p] = x; return ; } int mid=(l+r)>>1; spread(p); if(L<=mid) { update(p<<1,l,mid,L,R,x); } if(R>mid) { update(p<<1|1,mid+1,r,L,R,x); } }
long long ans = 0;
long long calc(int l,int r) { long long res=0; int nowR = r; int nowL = 0; while(nowR>=l) { nowL = max(ask_num(1,1,n,nowR),l); res += (long long) (get_pos(nowL)+get_pos(nowR))*(nowR-nowL+1)/2; nowR = nowL-1; } return res; }
void Go_Right(int x,int G) { int l=x,r=n; int y=-1; while(l<=r) { int mid=(l+r)>>1; if(get_pos(mid)<=G+mid-x) { y=mid; l=mid+1; } else { r=mid-1; } } ans-=calc(x,y); update(1,1,n,x,y,x); X[x] = G; ans+=calc(x,y); }
int Find_Right(int x) { int l=x+1,r=n; int res=0; while(l<=r) { int mid=(l+r)>>1; if(ask_num(1,1,n,mid)<=x) { res=mid; l=mid+1; } else { r=mid-1; } } return res; }
void Go_Left(int x,int G) { int l=1,r=x; int y=-1; while(l<=r) { int mid=(l+r)>>1; if(G-x+mid<=get_pos(mid)) { r=mid-1; y=mid; } else { l=mid+1; } }
int z = Find_Right(x); if(z!=0) { X[x+1] = get_pos(x+1); update(1,1,n,x+1,z,x+1); } ans+=calc(y,x); X[y] = G-x+y; update(1,1,n,y,x,y); ans-=calc(y,x); }
int main() { cin>>n; for(int i=1;i<=n;i++) { cin>>X[i]; } build(1,1,n); cin>>q; while(q--) { int T,G; cin>>T>>G; int nowP = get_pos(T); if(nowP<G) { Go_Right(T,G); } else if(nowP>G) { Go_Left(T,G); } } cout<<ans<<"\n"; return 0; }
|