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









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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值