Time limit : 2sec / Memory limit : 1024MB
Score : 400 points
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:
Input is given from Standard Input in the following format:
N M
A1 A2 … AN
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.
Copy
3 2
4 1 5
Copy
3
The sum Al+Al+1+…+Ar for each pair (l,r) is as follows:
Among these, three are multiples of 2.
13 17
29 7 5 7 9 51 7 13 8 55 42 9 81
6
10 400000000
1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000
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]);
}