Analysis
Consider the case where first. Since after the -th turn, the states of the coins are determined, and the states of the coins are unchanged, one can easily come up with the following dynamic programming solution: let be the maximum possible (signed) difference of the score of the current player and that of the other player, only considering the coins , where the state of the coin is head/tail. The initial value of the dp is , and the transition formula is . The answer is therfore the average value of and the sum of , which yields a solution with time complexity .
To solve the problem, one must find in a faster way. Consider . Expanding the recurrence, one can get and . It turns out that is exactly the doubled suffix minimum of ! Therefore one can write the explicit formula of , since . Therefore, the final answer is , where is the suffix minimum of .
One may use std::set to maintain the indices where the suffix minimum of changes. Since a modification only decreases the value of , it’s sufficient to insert a new element and delete all the previous element whose former suffix minimum is less than or equal to the value of after decreasing. Each time the set is changed, one can recalculate the answer in time. Since each element can be deleted at most once, the time complexity is .
Code
#include <bits/stdc++.h>
#define mp make_pair
#define fi first
#define se second
typedef long long ll;
using namespace std;
set<pair<int,ll> > S;
int n,q,p;ll s;
ll a[200005];
ll b[200005];
ll ans;
inline int query(int L,int R)
{
return (R%2==0)-(L%2==0);
}
int main()
{
ios_base::sync_with_stdio(false);cin.tie(0);
cin>>n;
for(int i=1;i<=n;++i)
{
cin>>a[i];
if(i&1) ans+=a[i];
}
for(int i=n;i>=2;--i)
{
if(i==n) b[i]=a[i];
else b[i]=min(b[i+1],a[i]);
if(i==n||b[i]!=b[i+1])
{
S.insert(mp(i,b[i]));
}
if(i&1) ans-=b[i];
else ans+=b[i];
}
S.insert(mp(1,0));
cout<<ans<<'\n';cin>>q;
while(q--)
{
cin>>p>>s;
a[p]-=s;
if(p&1) ans-=s;
if(p>1)
{
set<pair<int,ll> >::iterator itr=S.lower_bound(mp(p,0));
if(a[p]<(itr->se))
{
ans-=query(prev(itr)->fi,p)*((itr->se)-a[p]);
if((itr->fi)==p)
{
S.erase(itr);
}
S.insert(mp(p,a[p]));
int cur=p;
while(1)
{
itr=S.lower_bound(mp(cur,0));
--itr;
if((itr->se)<=a[p]) break;
ans-=query(prev(itr)->fi,itr->fi)*((itr->se)-a[p]);
S.erase(itr);
cur=itr->fi;
}
}
}
cout<<ans<<'\n';
}
return 0;
}