CodeForces 1333-C Eugene and an array(子区间和为0、前缀和)

http://codeforces.com/contest/1333/problem/C

 

大致题意:

如果一个子区间,它的任何子区间和都不为0,那么它很good,求这样的子区间的个数

 1 #include <bits/stdc++.h>
 2 typedef long long LL;
 3 const int INF=0x3f3f3f3f;
 4 const double eps =1e-8;
 5 const int mod=1e8;
 6 const int maxn=2e5+10;
 7 using namespace std;
 8 
 9 map<LL,LL> mp;
10 
11 int main()
12 {
13     #ifdef DEBUG
14     freopen("sample.txt","r",stdin);
15     #endif
16     
17     int n;
18     scanf("%d",&n);
19     LL pos=1;//记录当上一次出现区间和为0时的位置,初始为1(把数字0插到位置1) 
20     LL sum=0;//前缀和 
21     LL ans=0;
22     mp[0]=1;//数字0插到了位置1
23     for(int i=2;i<=n+1;i++)//相当于在最前面加了一个数字0,所以编号全+1 
24     {
25         int x;
26         scanf("%d",&x);
27         sum+=x;
28         if(mp.count(sum))
29         {
30             pos=max(pos,mp[sum]);
31             ans+=i-(pos+1)+1-1;//-1是因为区间[pos+1, i]和为0,要减去这一区间 
32         }
33         else ans+=i-(pos+1)+1;//加上区间[pos+1,i],[pos+2,i],[pos+3,i]...[i,i]
34         mp[sum]=i;
35     }
36     printf("%lld\n",ans);
37     
38     return 0;
39 }

-

猜你喜欢

转载自www.cnblogs.com/jiamian/p/12664197.html