https://codeforces.com/contest/1491/problem/C
思路:
枚举每个位置对后面的位置的贡献。因此需要开一个t数组维护一下。
对于x这个位置来说,会对后面的位置{x+2....min(x+Sx,n)}产生+1
对于x+1存在细节的谈判。对于上述操作做完之后,如果当前tx>=sx,说明这个经过这个点的次数有多余,但是此时经过这个点只能对x+1产生贡献。注意把刚才的+1加回去。
最后再累加扫一遍。
优化的话就对这个位置的+1上差分数组维护。
O(n^2)
#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=5e3+100;
typedef long long LL;
inline LL read(){LL x=0,f=1;char ch=getchar(); while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
return x*f;}
LL t[maxn];
LL s[maxn];
int main(void)
{
cin.tie(0);std::ios::sync_with_stdio(false);
LL T;cin>>T;
while(T--){
LL n;cin>>n;
for(LL i=0;i<n+10;i++) s[i]=t[i]=0;
for(LL i=1;i<=n;i++) cin>>s[i];
for(LL i=1;i<=n;i++){
for(LL j=i+2;j<=min(i+s[i],n);j++){
t[j]++;
}
}
for(LL i=1;i<n;i++){
if(t[i]>=s[i]) t[i+1]+=(t[i]-s[i]+1);
}
LL ans=0;
for(LL i=1;i<=n;i++){
ans+=max((LL)0,s[i]-t[i]-1);///不是减到0
}
cout<<ans<<"\n";
}
return 0;
}
O(n)
#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=5e3+100;
typedef long long LL;
inline LL read(){LL x=0,f=1;char ch=getchar(); while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
return x*f;}
LL t[maxn],cnt[maxn],s[maxn];
int main(void)
{
cin.tie(0);std::ios::sync_with_stdio(false);
LL T;cin>>T;
while(T--){
LL n;cin>>n;
for(LL i=0;i<n+10;i++) t[i]=cnt[i]=s[i]=0;
for(LL i=1;i<=n;i++) cin>>s[i];
for(LL i=1;i<=n;i++){
LL l=i+2;LL r=min(s[i]+i,n);
if(l<=r){
cnt[l]++;cnt[r+1]--;
}
}
for(LL i=1;i<=n;i++){
t[i]=t[i-1]+cnt[i];
}
for(LL i=1;i<=n;i++){
if(t[i]>=s[i]) t[i+1]+=(t[i]-s[i]+1);///上面原先部分的+1
}
LL ans=0;
for(LL i=1;i<=n;i++){
ans+=max((LL)0,s[i]-t[i]-1);
}
cout<<ans<<"\n";
}
return 0;
}