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<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1e5+5;
ll n,m,ans=0;
map<ll,ll>cnt;
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]);
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章