哈理工OJ HLG OJ 1005Counting Subsequences(map应用)(STL应用)

Counting Subsequences
Time Limit: 5000 MS Memory Limit: 65536 K
Total Submit: 698(203 users) Total Accepted: 180(156 users) Rating:  Special Judge: No
Description

 "47 is the quintessential random number," states the 47 society. And there might be a grain of truth in that.

For example, the first ten digits of the Euler's constant are:

2 7 1 8 2 8 1 8 2 8

And what's their sum? Of course, it is 47.

You are given a sequence S of integers we saw somewhere in the nature. Your task will be to compute how strongly does this sequence support the above claims.

We will call a continuous subsequence of S interesting if the sum of its terms is equal to 47.

E.g., consider the sequence S = (24, 17, 23, 24, 5, 47). Here we have two interesting continuous subsequences: the sequence (23, 24) and the sequence (47).

Given a sequence S, find the count of its interesting subsequences.

Input

The first line of the input file contains an integer T(T <= 10) specifying the number of test cases. Each test case is preceded by a blank line.

The first line of each test case contains the length of a sequence N(N <= 500000). The second line contains N space-separated integers – the elements of the sequence. Sum of any continuous subsequences will fit in 32 bit signed integers.

Output

For each test case output a single line containing a single integer – the count of interesting subsequences of the given sentence.

Sample Input
2
 
13
2 7 1 8 2 8 1 8 2 8 4 5 9
 
7
2 47 10047 47 1047 47 47
Sample Output
3
4

一开始还觉得是DP方面的题目。。。。。

这里先说明题目大意:找到一共有多少序列能够加和==47.如果有+1.输出最终结果就可以。

这里题目的解题思路还是很清晰的:用一个sum(起始当然为0)每一次输入都+上输入的数字,然后看看-47之后有没有这个数:例如样例1中,sum是这样变化的:

0 2 9 10 18 20 28 29 37 39 47 51 56 65.当我们加到47的时候,-47,发现有0,就说明这个序列已经是正好加==47的序列。再例如加到65的时候-47得18,我们发现18也出现过,所以我们这里又发现了一个序列正好加==47.我们这里要应用一个标记的问题。

N(N <= 500000)

这里我们发现N的数据范围是很大的,说明后台数据足够多,然而每一次输入的数据保证int但是int最大值*500000也是我们开一维数组吃不消的范围,所以我们这里应用map来解决问题:

直接上完整的AC代码:

#include<stdio.h>
#include<string.h>
#include<map>
using namespace std;
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int n;
        scanf("%d",&n);
        map<int,int >s;
        s.clear();//谨慎一点好。
        int sum=0;
        int output=0;
        s[0]=1;
        for(int i=0;i<n;i++)
        {
            int a;
            scanf("%d",&a);
            sum+=a;
            s[sum]++;
            output+=s[sum-47];
        }
        printf("%d\n",output);
    }
}


















你可能感兴趣的:(1005,1005,1005,哈理工oj,哈理工)