time limit per test :1.5 seconds memory limit per test :256 megabytes
inputstandard input outputstandard output
Eugene likes working with arrays. And today he needs your help in solving one challenging task.
An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array [−1,2,−3] is good, as all arrays [−1], [−1,2], [−1,2,−3], [2], [2,−3], [−3] have nonzero sums of elements. However, array [−1,2,−1,−3] isn't good, as his subarray [−1,2,−1] has sum of elements equal to 0.
Help Eugene to calculate the number of nonempty good subarrays of a given array a.
The first line of the input contains a single integer n (1≤n≤2×105) — the length of array a.
The second line of the input contains n integers a1,a2,…,an (−109≤ai≤109) — the elements of a.
Output a single integer — the number of good subarrays of a.
3
1 2 -3
5
3
41 -41 41
3
In the first sample, the following subarrays are good: [1], [1,2], [2], [2,−3], [−3]. However, the subarray [1,2,−3] isn't good, as its subarray [1,2,−3] has sum of elements equal to 0.
In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray [41,−41,41] isn't good, as its subarray [41,−41] has sum of elements equal to 0.
给一个长度为n的数组a,问有多少子串满足没有和为0的子串?
这个是一个计数题,对于计数题我们要做到不重不漏,一开始我是前缀和然后排序再处理,完全跑偏(不能排序,但是我一直没发现),不管怎么做都会算重或算漏。
#include
using namespace std;
#define pb push_back
#define mp make_pair
#define fi first
#define se second
typedef long long ll;
typedef unsigned long long ull;
typedef pair PII;
const int mod = 1e9 + 7;
const int N = 2e5 + 10;
const int INF = 0x3f3f3f3f;
ll qpow(ll base, ll n){ll ans = 1; while (n){if (n & 1) ans = ans * base % mod; base = base * base % mod; n >>= 1;} return ans;}
ll gcd(ll a, ll b){return b ? gcd(b, a % b) : a;}
map pos;
int main()
{
int n;
cin >> n;
ll tmp, sum = 0, ans = 0;
pos[0] = 0;
int pre = -1;
for (int i = 1; i <= n; ++ i){
scanf("%lld", &tmp);
sum += tmp;
if (pos.count(sum))pre = max(pre, pos[sum]);
ans += i - pre - 1;
pos[sum] = i;
}
cout << ans << endl;
return 0;
}