#640(Div.4)E. Special Elements(前缀和)

题目描述

Pay attention to the non-standard memory limit in this problem.
In order to cut off efficient solutions from inefficient ones in this problem, the time limit is rather strict. Prefer to use compiled statically typed languages (e.g. C++). If you use Python, then submit solutions on PyPy. Try to write an efficient solution.
The array a=[a1,a2,…,an] (1≤ai≤n) is given. Its element ai is called special if there exists a pair of indices l and r (1≤l<r≤n) such that ai=al+al+1+…+ar. In other words, an element is called special if it can be represented as the sum of two or more consecutive elements of an array (no matter if they are special or not).
Print the number of special elements of the given array a.
For example, if n=9 and a=[3,1,4,1,5,9,2,6,5], then the answer is 5:
a3=4 is a special element, since a3=4=a1+a2=3+1;
a5=5 is a special element, since a5=5=a2+a3=1+4;
a6=9 is a special element, since a6=9=a1+a2+a3+a4=3+1+4+1;
a8=6 is a special element, since a8=6=a2+a3+a4=1+4+1;
a9=5 is a special element, since a9=5=a2+a3=1+4.
Please note that some of the elements of the array a may be equal — if several elements are equal and special, then all of them should be counted in the answer.

Input

The first line contains an integer t (1≤t≤1000) — the number of test cases in the input. Then t test cases follow.
Each test case is given in two lines. The first line contains an integer n (1≤n≤8000) — the length of the array a. The second line contains integers a1,a2,…,an (1≤ai≤n).
It is guaranteed that the sum of the values of n for all test cases in the input does not exceed 8000.

Output

Print t numbers — the number of special elements for each of the given arrays.

Example

input
5
9
3 1 4 1 5 9 2 6 5
3
1 1 2
5
1 1 1 1 1
8
8 7 6 5 4 3 2 1
1
1
output
5
1
0
4
0

题目大意

给定n个数,如果a[i]=sum(a[l-r])(1<=l<r<=n),那么称a[i]为一个特殊数,求这n个数中特殊数的个数。

题目分析

因为数据范围只有8000,所以可以用O(n2)的做法。
首先用一个“桶”,将这n个数装起来(到时候方便查询)。然后将a数组前缀和处理。
枚举a[]所有区间的和,同时进行查询a[]中原来是否有这个数,如果有则加上这个数的个数即可。

代码如下
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <unordered_map>
#include <queue>
#include <vector>
#include <set> 
#include <algorithm>
#include <iomanip>
#define LL long long
using namespace std;
int const N=8e3+1;
int main()
{
	int t;
	cin>>t;
	while(t--)
	{
		int n;
		scanf("%d",&n);
		int a[N],ma[N]={0};
		for(int i=1;i<=n;i++)    //输入+装桶+前缀和
		{
			scanf("%d",&a[i]); 
			ma[a[i]]++;
			a[i]+=a[i-1];
		}
		int cnt=0;          //特殊数的个数
		for(int i=1;i<=n;i++)
		for(int j=i+1;j<=n;j++)
		{   //枚举每一段区间
			int sum=a[j]-a[i-1];     //sum表示区间的和
			if(sum<=n&&ma[sum]) cnt+=ma[sum],ma[sum]=0;   //防止越界与加重
		}
		printf("%d\n",cnt);     //输出答案即可
	}
    return 0;
}

猜你喜欢

转载自blog.csdn.net/li_wen_zhuo/article/details/106033722
今日推荐