SPOJ CRAN02 - Roommate Agreement

题目链接http://www.spoj.com/problems/CRAN02/

题目大意:N个数字组成的序列,和为0的连续子序列的个数。N<1e6

解题思路:计算前缀和,统计每个数字出现的次数,那么对于数字sum[i], 如果存在k个sum[i],则代表有C(k, 2)个序列和为0,而如果sum[i] = 0,则还要累加上对应的k值。

代码:

 1 ll n;
 2 int a[maxn];
 3 ll sum[maxn];
 4 map<int, int> mmp;
 5 
 6 void solve(){
 7     memset(sum, 0, sizeof(sum));
 8     for(int i = 1; i <= n; i++) {
 9         sum[i] = sum[i - 1] + a[i];
10         mmp[sum[i]]++;
11     }
12     ll ans = 0;
13     for(int i = 1; i <= n; i++){
14         ll k = mmp[sum[i]];
15         if(sum[i] == 0) ans += k;
16         mmp[sum[i]] = 0;
17         if(k >= 2) ans += k * (k - 1) / 2;
18     }
19     printf("%lld\n",ans);
20 } 
21 int main(){
22     int t;
23     scanf("%d", &t);
24     for(int i = 1; i <= t; i++){
25         mmp.clear();
26         scanf("%lld", &n);
27         for(int j = 1; j <= n; j++) 
28             scanf("%d", &a[j]);
29         solve();
30     }
31 }

题目:

CRAN02 - Roommate Agreement

 

Leonard was always sickened by how Sheldon considered himself better than him. To decide once and for all who is better among them they decided to ask each other a puzzle. Sheldon pointed out that according to Roommate Agreement Sheldon will ask first. Leonard seeing an opportunity decided that the winner will get to rewrite the Roommate Agreement.

Sheldon thought for a moment then agreed to the terms thinking that Leonard will never be able to answer right. For Leonard, Sheldon thought of a puzzle which is as follows. He gave Leonard n numbers, which can be both positive and negative. Leonard had to find the number of continuous sequence of numbers such that their sum is zero.

 For example if the sequence is- 5, 2, -2, 5, -5, 9

There are 3 such sequences

2, -2

5, -5

2, -2, 5, -5

Since this is a golden opportunity for Leonard to rewrite the Roommate Agreement and get rid of Sheldon's ridiculous clauses, he can't afford to lose. So he turns to you for help. Don't let him down.

 

Input

First line contains T - number of test cases

Second line contains n - the number of elements in a particular test case.

Next line contain n elements, ai  (1<=i<= n) separated by spaces.

 

Output

The number of such sequences whose sum if zero.

 

Constraints

1<=t<=5

1<=n<=10^6

-10<= ai <= 10

 

Example

Input:

2

4

0 1 -1 0

6

5 2 -2 5 -5 9

Output:

6
3

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值