1795E - Explosions - CodeForces Solution


data structures dp greedy math

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
#define all(x) (x).begin(),(x).end()
using namespace std;
typedef long long ll;
constexpr int N=3e5+5;
int n,a[N],w[N],q[N],hd,tl,cnt[N];ll pre[N],suf[N];
int main(){
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	int T;cin>>T;while(T--){
		cin>>n;
		for(int i=1;i<=n;i++){
			cin>>a[i];
		}
		ll ans=0;hd=1;tl=0;
		for(int i=1,l=0;i<=n;i++){
			w[i]=a[i]-i;cnt[i]=1;l=max(l,-w[i]);
			for(;hd<=tl&&q[hd]-cnt[q[hd]]<l;hd++){
				ans+=1ll*w[q[hd]]*(l-q[hd]+cnt[q[hd]]);
				ans+=1ll*(l+q[hd]-cnt[q[hd]]+1)*(l-q[hd]+cnt[q[hd]])/2;
				cnt[q[hd]]=q[hd]-l;
				if(cnt[q[hd]])break;
			}
			for(;hd<=tl&&w[q[tl]]>=w[i];tl--){
				ans+=(w[q[tl]]-w[i])*cnt[q[tl]];
				cnt[i]+=cnt[q[tl]];
			}
			pre[i]=ans;
			q[++tl]=i;
		}
		reverse(a+1,a+n+1);
		ans=0;hd=1;tl=0;
		for(int i=1,l=0;i<=n;i++){
			w[i]=a[i]-i;cnt[i]=1;l=max(l,-w[i]);
			for(;hd<=tl&&q[hd]-cnt[q[hd]]<l;hd++){
				ans+=1ll*w[q[hd]]*(l-q[hd]+cnt[q[hd]]);
				ans+=1ll*(l+q[hd]-cnt[q[hd]]+1)*(l-q[hd]+cnt[q[hd]])/2;
				cnt[q[hd]]=q[hd]-l;
				if(cnt[q[hd]])break;
			}
			for(;hd<=tl&&w[q[tl]]>=w[i];tl--){
				ans+=(w[q[tl]]-w[i])*cnt[q[tl]];
				cnt[i]+=cnt[q[tl]];
			}
			suf[n-i+1]=ans;
			q[++tl]=i;
		}
		reverse(a+1,a+n+1);
		ans=0;
		for(int i=1;i<=n;i++){
			ans+=a[i];
		}
		for(int i=1;i<=n;i++){
			//printf("%d: a=%d,pre=%lld,suf=%lld\n",i,a[i],pre[i],suf[i]);
			ans=min(ans,a[i]+pre[i]+suf[i]);
		}
		printf("%lld\n",ans);
	}
	return 0;
}
   				 		 			  					 	 				


Comments

Submit
0 Comments
More Questions

337A - Puzzles
495A - Digital Counter
796A - Buying A House
67A - Partial Teacher
116A - Tram
1472B - Fair Division
1281C - Cut and Paste
141A - Amusing Joke
112A - Petya and Strings
677A - Vanya and Fence
1621A - Stable Arrangement of Rooks
472A - Design Tutorial Learn from Math
1368A - C+=
450A - Jzzhu and Children
546A - Soldier and Bananas
32B - Borze
1651B - Prove Him Wrong
381A - Sereja and Dima
41A - Translation
1559A - Mocha and Math
832A - Sasha and Sticks
292B - Network Topology
1339A - Filling Diamonds
910A - The Way to Home
617A - Elephant
48A - Rock-paper-scissors
294A - Shaass and Oskols
1213A - Chips Moving
490A - Team Olympiad
233A - Perfect Permutation