码迷,mamicode.com
首页 > 其他好文 > 详细

SPOJ-CRAN02 - Roommate Agreement(前缀和)

时间:2017-02-21 01:15:31      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:.com   namespace   fine   class   cond   get   exp   bit   efi   

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

题意

给你一个序列,里面n(10^6)个数字,问这些数字相加为0的区间有多少个

思路

看样例解释我们可以知道,可以利用前缀和来计算,a[i]=a[i]+a[i-1]这样,然后用map来存a[i]出现的次数,

 1 /*
 2     Name: hello world.cpp
 3     Author: AA
 4     Description: 唯代码与你不可辜负
 5 */
 6 #include<bits/stdc++.h>
 7 using namespace std;
 8 #define LL long long
 9 int main() {
10     int t;
11     cin >> t;
12     while(t--) {
13         int n;
14         cin >> n;
15         LL a[n];
16         map<LL, LL> cnt;
17         cin >> a[0];
18         cnt[a[0]]++;
19         for(int i = 1; i < n; i++) {
20             cin >> a[i];
21             a[i] += a[i - 1];
22             cnt[a[i]]++;
23         }
24         map<LL, LL>::iterator it;
25         LL ans = 0;
26         for(it = cnt.begin(); it != cnt.end(); it++) {
27             if(it->first == 0)
28                 ans += it->second + it->second * (it->second - 1) / 2;
29             else
30                 ans += it->second * (it->second - 1) / 2;
31         }
32         cout << ans << endl;
33     }
34     return 0;
35 }

 

SPOJ-CRAN02 - Roommate Agreement(前缀和)

标签:.com   namespace   fine   class   cond   get   exp   bit   efi   

原文地址:http://www.cnblogs.com/zhien-aa/p/6422209.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!