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]);
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值