Educational Codeforces Round 93 (Rated for Div. 2) C. Good Subarrays
阿新 • • 發佈:2020-08-17
C. Good Subarrays
原題連結:https://codeforces.ml/contest/1398/problem/C
題目大意:
給定一個序列,序列中的數為$0,1...9$,求有多少個連續子序列的和等於它的長度。
解題思路:
首先將所有的數都減去1,就可以轉化為求有多少個區間和為0,可以維護一個字首和,當前$i$個數的字首和等於前$j$個數,則說明$(i,j]$這個區間和為0,所以記錄每個字首和的個數,然後遍歷序列即可。要注意的是初始化時$dp_0 = 1$。
程式碼:
1 #include <bits/stdc++.h>
2 using namespace std;
3 typedef long long ll;
4 typedef pair<ll,ll> pi;
5 typedef complex <double> cp;
6 #define debug(a) cout<<#a<<":"<<a<<endl;
7 #define fr freopen("in.txt","r",stdin);
8 #define Fill(x,a) memset(x,a,sizeof(x))
9 #define cpy(a,b) memcpy(a,b,sizeof(a))
10 const double PI = acos(-1 );
11 const ll INF=0x3f3f3f3f;
12 const ll N=1e6+7;
13 const ll mod=1e9+7;
14 ll maxn,minn;
15 ll T,n,m,q;
16 string s;
17 ll arr[N];
18 map<int,int>mp;
19
20
21 int main(){
22 ll ans,res;
23 cin>>T;
24 while(T--){
25 cin>>n>>s;
26 ans=res=0;
27 mp.clear();
28 for(ll i=0;i<n;i++){
29 arr[i+1]=s[i]-'0'-1;
30 }
31 mp[0]=1;
32 for(ll i=1;i<=n;i++){
33 res+=arr[i];
34 ans=ans+mp[res];
35 mp[res]++;
36 }
37 cout<<ans<<endl;
38
39 }
40
41
42 return 0;
43 }
44