CodeForces - 1485F Copy or Prefix Sum(dp)
題目鏈接:點擊查看
題目大意:給出數組 bbb,問可以構造出多少種滿足條件的數組 aaa,規定數組 aaa 和數組 bbb 的關系如下:
題目分析:乍一看是個計數問題,因為對于每個位置,aia_iai? 都有兩種選擇,所以答案將會是 2n2^n2n 級別的,但是有些時候會重復計數,觀察當 (∑j=1i?1aj)=0(\sum_{j=1}^{i-1} a_j)=0(∑j=1i?1?aj?)=0 時,aia_iai? 有且僅有一種選擇,那就是等于 bib_ibi? 了
所以先設計一個 n2n^2n2 級別的 dpdpdp,dpi,jdp_{i,j}dpi,j? 代表到了第 iii 個位置,前綴和為 jjj 時的方案數,轉移的話也是比較簡單,可以分別從上面兩種情況進行轉移:
注意上面第二種情況減去的 dp[i?1][0]dp[i-1][0]dp[i?1][0] 就是去掉 sum=0sum=0sum=0 的方案數
考慮其實很多轉移都是無用的,也就是統一偏移了固定的單位,所以我們可以參考 “水平線優化dp” 的博客:https://codeforces.com/blog/entry/58316
維護一個偏移量輔助轉移,這樣第一種情況就可以直接 O(1)O(1)O(1) 維護了,而對于第二種情況,也只是需要單獨查一下 dp[i?1][0]dp[i-1][0]dp[i?1][0] 這一項,剩下的將 dpdpdp 數組滾動一下就可以了
代碼:
// Problem: F. Copy or Prefix Sum // Contest: Codeforces - Codeforces Round #701 (Div. 2) // URL: https://codeforces.com/contest/1485/problem/F // 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; const int mod=1e9+7; map<LL,LL>mp; 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--) {mp.clear();int n;read(n);LL delta=0,ans=1;mp[0]=1;for(int i=1;i<=n;i++) {int x;read(x);LL temp=(ans-mp[-delta]+mod)%mod;mp[-delta]=(mp[-delta]+temp)%mod;delta+=x;ans=(ans+temp)%mod;}cout<<ans<<endl;}return 0; }總結
以上是生活随笔為你收集整理的CodeForces - 1485F Copy or Prefix Sum(dp)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CodeForces - 1485E M
- 下一篇: CodeForces - 1538G G