思路:dp。
代码:
#include<bits/stdc++.h> using namespace std; #define ll long long #define pb push_back #define mem(a,b) memset(a,b,sizeof(a) const int N=1e5+5; ll dp[N]={0}; ll dp1[N]={0}; ll a[N]; ll t[N]={0}; ll t1[N]={0}; int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin>>n; for(int i=1;i<=n;i++)cin>>a[i]; t[1]=a[1]; for(int i=2;i<=n;i++) { if(a[i]<=t[i-1]) { dp[i]=dp[i-1]+t[i-1]-a[i]+1; t[i]=t[i-1]+1; } else { t[i]=a[i]; dp[i]=dp[i-1]; } } t1[n]=a[n]; for(int i=n-1;i>=1;i--) { if(a[i]<=t1[i+1]) { dp1[i]=dp1[i+1]+t1[i+1]-a[i]+1; t1[i]=t1[i+1]+1; } else { t1[i]=a[i]; dp1[i]=dp1[i+1]; } } ll ans=min(dp1[1],dp[n]); for(int i=2;i<=n-1;i++) ans=min(ans,dp1[i]+dp[i]-min(t[i],t1[i])+a[i]); cout<<ans<<endl; return 0; }