Atcoder Candy Distribution II

题目描述
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≤10^5
·2≤M≤10^9
·1≤Ai≤10^9
输入
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.

样例输入
3 2
4 1 5
样例输出
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.

题意比较明确了,就是找出连续的子序列,让他们的和能正好被m整除。
乍一看就是像一个前缀和的题,但是暴力枚举的话肯定就超时了,注意到每一段可以用两个前缀和之差来表示,所以可以分两种讨论。
(1)如果一个初始前缀和对m取模为0的话,一定可以,所以直接加上即可。
(2)如果两个前缀和对m取模后,差值为0,也就是说他们的余数相同,做差后可以消去余数,那么从这些数中选两个做差即可,也就是C ( n , 2 ) 。
可以用map来存每个前缀和对m取模后的值,遍历可以得到答案。
还有注意用LL存,答案比较大。

#include<cstdio>
#include<iostream>
#include<string>
#include<cstring>
#include<map>
#include<vector>
#include<set>
#include<queue>
#include<algorithm>
#include<sstream>
#define X first
#define Y second
using namespace std;

typedef long long LL;
typedef pair<int,int> PII;

const int N=1000010,mod=1e9+7;

LL gcd(LL a,LL b) {return b? gcd(b,a%b):a;};

LL n,m;
LL sum[N],a[N];
map<LL,LL>mp;

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);

	cin>>n>>m;

	for(int i=1;i<=n;i++)
	{
		cin>>a[i];
		sum[i]=(sum[i-1]+a[i])%m;
		mp[sum[i]]++;
	}
	
	LL ans=mp[0];
	
	for(map<LL,LL>::iterator it=mp.begin();it!=mp.end();it++)
		ans+=it->Y*(it->Y-1)/2;
	
	cout<<ans<<endl;





	return 0;
}









发布了43 篇原创文章 · 获赞 1 · 访问量 1578

猜你喜欢

转载自blog.csdn.net/DaNIelLAk/article/details/104866748