SPOJ-CRAN02 - Roommate Agreement(前缀和)

Posted tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SPOJ-CRAN02 - Roommate Agreement(前缀和)相关的知识,希望对你有一定的参考价值。

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(前缀和)的主要内容,如果未能解决你的问题,请参考以下文章

在 ag 网格输入中只允许十进制值

ag-grid :- enableMultiRowDragging 在 ag-grid 24 中不起作用

在 Parse Query 中初始化或修改变量

Ag-Grid - 访问所有数据 - 包括计算列

角度 ag 网格不适用于角度 5

您如何在 ag-grid 模块中使用多个组件?