Codeforces Round #632 (Div. 2) C. Eugene and an array
阿新 • • 發佈:2020-08-16
題目連結:https://codeforc.es/contest/1333/problem/C
題意:給定一個數組,問有多少個連續子陣列滿足 是好陣列 一個數組中的任意連續子陣列和都不為0的陣列為好陣列
思路: 考慮到 每個子陣列可以通過 起點和長度來確定, 那麼就列舉每個起點, 在找到前面第一個不符合的狀態
要記錄陣列和的狀態 就要用字首和, sum[i]-sum[j-1] ==0 的時候 就說明j~i 這一段是不符合好陣列的
那麼記錄每個sum 的最近的位置即可 當然要注意要用 一個 max1來維護,因為 中間有一部分為0的話,就不能到前面了
如 字首和 1 2 2 1 此時 中間的22 就已經不滿足了
處理的時候 要注意一下邊界的問題, 可以讓i=2 開始 更好的處理
1 #include<bits/stdc++.h> 2 using namespace std; 3 #define ll long long 4 #define ull unsigned long long 5 #define pb push_back 6 const int maxn=2e5+10; 7 const int mod=1e9+7; 8 ll a[maxn]; 9 10 11 int main() 12 { 13 ios::sync_with_stdio(false); 14 cin.tie(0); 15 int n; 16View Codecin>>n; 17 for(int i=2;i<=n+1;i++) 18 { 19 cin>>a[i]; 20 } 21 map<ll,ll>mp; 22 ll sum=0; 23 ll ans=0; 24 ll max1=0; 25 mp[0]=1; 26 for(int i=2;i<=n+1;i++) 27 { 28 sum+=a[i]; 29 max1=max(max1,mp[sum]); 30 inttemp=i-max1-1; 31 ans+=temp; 32 mp[sum]=i; 33 34 } 35 cout<<ans<<'\n'; 36 37 38 39 40 }
正常i=1開始的處理
1 #include<bits/stdc++.h> 2 using namespace std; 3 #define ll long long 4 #define ull unsigned long long 5 #define pb push_back 6 const int maxn=2e5+10; 7 const int mod=1e9+7; 8 ll a[maxn]; 9 10 11 int main() 12 { 13 ios::sync_with_stdio(false); 14 cin.tie(0); 15 int n; 16 cin>>n; 17 for(int i=1;i<=n;i++) 18 { 19 cin>>a[i]; 20 } 21 map<ll,ll>mp; 22 ll sum=0; 23 ll ans=0; 24 ll max1=0; 25 mp[0]=1; 26 for(int i=1;i<=n;i++) 27 { 28 sum+=a[i]; 29 max1=max(max1,mp[sum]); 30 int temp=i-max1; 31 /*if(max1==0&&sum!=0) 32 temp++;*/ 33 ans+=temp; 34 mp[sum]=i+1; 35 } 36 cout<<ans<<'\n'; 37 38 39 40 41 }View Code
錯誤的處理
1 #include<bits/stdc++.h> 2 using namespace std; 3 #define ll long long 4 #define ull unsigned long long 5 #define pb push_back 6 const int maxn=2e5+10; 7 const int mod=1e9+7; 8 ll a[maxn]; 9 10 11 int main() 12 { 13 ios::sync_with_stdio(false); 14 cin.tie(0); 15 int n; 16 cin>>n; 17 for(int i=1;i<=n;i++) 18 { 19 cin>>a[i]; 20 } 21 map<ll,ll>mp; 22 ll sum=0; 23 ll ans=0; 24 ll max1=0; 25 for(int i=1;i<=n;i++) 26 { 27 sum+=a[i]; 28 max1=max(max1,mp[sum]); 29 int temp=i-max1-1; 30 if(max1==0&&sum!=0) 31 temp++; 32 ans+=temp; 33 mp[sum]=i; 34 35 36 } 37 cout<<ans<<'\n'; 38 39 40 41 42 }View Code
只是單獨考慮的0的時候-1 沒有考慮到0的位置對後面的影響 如字首和 0 2 3 4 0 5