CodeForces - 1491C Pekora and Trampoline(差分+贪心)
題目鏈接:點擊查看
題目大意:給出一個長度為 nnn 的序列 aaa,aia_iai? 表示第 iii 個蹦床的強度,當從第 iii 個蹦床起跳的話可以跳到 i+aii+a_ii+ai? 的位置,但是相應的第 iii 個蹦床的強度會減少一,更具體的來說,假如在蹦床 iii 起跳后,會有 ai=max(ai?1,1)a_i=max(a_i-1,1)ai?=max(ai??1,1)。問最小需要多少次彈跳,才能使得所有的蹦床強度都等于 111
題目分析:口胡了一個 n2n^2n2 的算法,交了一發之后發現會被卡成 n3n^3n3,看了看題解發現大家都是 O(n)O(n)O(n) 寫的。。拉低了全網的平均水平我真的很抱歉 orz
因為蹦床只能從前往后蹦,所以考慮從前往后貪心,假設 iii 位置為 aia_iai?,為了讓 aia_iai? 變成 111,肯定是需要直接或間接 ai?1a_i-1ai??1 次以點 iii 為起點開始往后跳的,而從 iii 為起點的話,那么 [i+2,min(n,i+ai)][i+2,min(n,i+a_i)][i+2,min(n,i+ai?)] 這一段區間的蹦床會間接成為一次起點
考慮模擬上述過程,因為數據范圍允許 O(n2)O(n^2)O(n2),所以可以直接暴力更新所有間接當作起點的位置,當到達某個位置 iii 后,分兩種情況討論一下即可,假設 cnticnt_icnti? 為點 iii 間接當做起點的次數
上述是 O(n2)O(n^2)O(n2) 的做法,考慮到瓶頸在于區間更新,所以可以用差分代替,直接用前綴和平推過去就好啦,最后時間復雜度優化成了 O(n)O(n)O(n)
代碼:
// Problem: C. Pekora and Trampoline // Contest: Codeforces - Codeforces Global Round 13 // URL: https://codeforces.com/contest/1491/problem/C // Memory Limit: 256 MB // Time Limit: 2000 ms // // Powered by CP Editor (https://cpeditor.org)// #pragma GCC optimize(2) // #pragma GCC optimize("Ofast","inline","-ffast-math") // #pragma GCC target("avx,sse2,sse3,sse4,mmx") #include<iostream> #include<cstdio> #include<string> #include<ctime> #include<cmath> #include<cstring> #include<algorithm> #include<stack> #include<climits> #include<queue> #include<map> #include<set> #include<sstream> #include<cassert> #include<bitset> #include<list> #include<unordered_map> #define lowbit(x) x&-x using namespace std; typedef long long LL; typedef unsigned long long ull; template<typename T> inline void read(T &x) {T f=1;x=0;char ch=getchar();while(0==isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}while(0!=isdigit(ch)) x=(x<<1)+(x<<3)+ch-'0',ch=getchar();x*=f; } template<typename T> inline void write(T x) {if(x<0){x=~(x-1);putchar('-');}if(x>9)write(x/10);putchar(x%10+'0'); } const int inf=0x3f3f3f3f; const int N=1e6+100; LL a[N],delta[N]; void add(int l,int r,int val) {if(l>r) {return;}delta[l]+=val;delta[r+1]-=val; } int main() { #ifndef ONLINE_JUDGE // freopen("data.in.txt","r",stdin); // freopen("data.out.txt","w",stdout); #endif // ios::sync_with_stdio(false);int w;cin>>w;while(w--) {int n;read(n);memset(delta,0,sizeof(LL)*(n+5));for(int i=1;i<=n;i++) {read(a[i]);}LL ans=0;for(int i=1;i<=n;i++) {delta[i]+=delta[i-1];if(delta[i]<a[i]-1) {//不夠ans+=(a[i]-1)-delta[i];} else {//夠了add(i+1,i+1,delta[i]-(a[i]-1));}add(i+2,min(1LL*n,i+a[i]),1);}cout<<ans<<endl;}return 0; }總結
以上是生活随笔為你收集整理的CodeForces - 1491C Pekora and Trampoline(差分+贪心)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CodeForces - 1523E C
- 下一篇: CodeForces - 1491E F