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
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
题意:
给一个数列,求有多少个数对【l,r】使得,位置l->r的项的和为m的倍数。
解题思路:
对整个数列求前缀和,并对m取余数,那么当第l项和第r项mod m同余时,就是合乎要求的。
所以扫一遍r,使r分别等于1->n。用map记录每种余数对应的l的个数。
(不可能用数组来记录1E9种余数,一共只有1e5个数,最多只有1e5个值,用map把余数和个数对应起来)
当第r项的前缀和的余数为x时,那么与其配对的l的个数,即之前余数为x的个数。
且当位置i的前缀和可以被m除尽时,是可以以第一项为起点的。要在结果中补上。
思路来源:D - Candy Distribution(atcoder) (前缀和+取余技巧)
#include<stdio.h>
#include<map>
#define maxn 100005
using namespace std;
long long remainder[maxn];
long long a[maxn];
map<long long,long long>number_l;
int main()
{
long long n,m,answer=0;
scanf("%lld%lld",&n,&m);
for(int i=1;i<=n;i++)
{
scanf("%lld",&a[i]);
remainder[i]=remainder[i-1]+a[i];
remainder[i]%=m;
answer+=number_l[remainder[i]];
number_l[remainder[i]]++;
}
answer+=number_l[0];/**0为起点自己为终点没有算进去,要补上**/
printf("%lld\n",answer);
return 0;
}
本文介绍了一种利用前缀和与取余数技巧解决特定数学问题的方法,核心在于通过计算数列的前缀和并对其取余,找到满足条件的数对,以确定数列中某段连续元素的和是否为给定数的倍数。
254

被折叠的 条评论
为什么被折叠?



