D - Candy Distribution Beginner Contest 105(子序列和是m的倍数的个数)

Problem Statement
There are N boxes arranged in a row from left to right. The i-th box from the left contains Ai candies.

You will take out the candies from some consecutive boxes and distribute them evenly to M children.

Such being the case, find the number of the pairs (l,r) that satisfy the following:

l and r are both integers and satisfy 1≤l≤r≤N.
Al+Al+1+…+Ar is a multiple of M.
Constraints
All values in input are integers.
1≤N≤105
2≤M≤109
1≤Ai≤109
Input
Input is given from Standard Input in the following format:

N M
A1 A2 … AN
Output
Print the number of the pairs (l,r) that satisfy the conditions.

Note that the number may not fit into a 32-bit integer type.

Sample Input 1
Copy
3 2
4 1 5
Sample Output 1
3
The sum Al+Al+1+…+Ar for each pair (l,r) is as follows:

Sum for (1,1): 4
Sum for (1,2): 5
Sum for (1,3): 10
Sum for (2,2): 1
Sum for (2,3): 6
Sum for (3,3): 5
Among these, three are multiples of 2.

Sample Input 2
13 17
29 7 5 7 9 51 7 13 8 55 42 9 81
Sample Output 2
6
Sample Input 3
10 400000000
1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000
Sample Output 3
25
记录前缀和,从和相等的里面挑两个即C(s,2)

#include 

using namespace std;
typedef long long LL;
int sum[1000000];

int main()
{
    LL n,m;
    while(scanf("%lld%lld",&n,&m)==2){
        LL x;
        sum[0]=0;
        for(LL i=1;i<=n;i++){
            scanf("%lld",&x);
            sum[i]=((sum[i-1]+x)%m+m)%m;
        }
        sort(sum,sum+n+1);
        LL s=1;
        long long ans=0;
        for(LL i=1;i<=n;i++){
            if(sum[i]==sum[i-1]) s++;
            else{
                ans+=s*(s-1)/2;
                s=1;
            }
        }
        ans+=s*(s-1)/2;
        printf("%lld\n",ans);
    }
    return 0;
}

你可能感兴趣的:(AtCoder)