D - Candy Distribution(atcoder) (前缀和+取余技巧)

D - Candy Distribution

Time limit : 2sec / Memory limit : 1024MB

Score : 400 points

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≤lrN.
  • Al+Al+1+…+Ar is a multiple of M.

Constraints

  • All values in input are integers.
  • 1≤N≤10^5
  • 2≤M≤10^9
  • 1≤Ai≤10^9

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

Copy

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

题意:给定n个数,求有多少对区间【i,j】和是m的倍数。

首先,前缀和sum[i]表示[1,i]的区间和,那么[L,R]的区间和即为sum[R]-sum[L-1].已知(sum[R]-sum[L-1])%m=0,得到sum[R]%m=sum[L-1]%m。当我们遍历到R时,只需要知道sum[R]%m的出现次数就行了,同时更新cnt[sum[R]%m]++。注意,如果a[i]%m=0,那么这种情况是有疏漏的,需要最后输出的时候加上cnt[0]。

#include
using namespace std;
typedef long long ll;
const int maxn=1e5+5;
ll n,m,ans=0;
mapcnt;
ll sum[maxn],num[maxn];
int main()
{
    scanf("%d%d",&n,&m);
    sum[0]=0;
    for(int i=1;i<=n;i++)
    {
        scanf("%lld",&num[i]);
        sum[i]=(sum[i-1]+num[i])%m;
        ans+=cnt[sum[i]];
        cnt[sum[i]]++;
    }
    printf("%lld\n",ans+cnt[0]);
}

 

你可能感兴趣的:(ACM之递推专题)