Candy Distribution II

时间限制: 1 Sec 内存限制: 128 MB
[提交] [状态]
题目描述
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.

样例输入 Copy

3 2
4 1 5

样例输出 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.
题目大意是求满足区间[l,r]内所有连续的数之和能整除M的区间个数。
一想到某个区间的连续的数之和,可以考虑前缀和。根据题意,即寻找满足(s[r]-s[l-1])%m==0的个数。第一思路是利用两个for循环嵌套来枚举所有情况,但是,这个题目的数据量太大,最后肯定会TLE,而且题干中输出那一栏中提示了结果不一定是int型,也就是说,存在计数变量(如cnt)从0一个个增加到2^31-1以上的情况,这样也会导致TLE。
我们可以从等式(s[r]-s[l-1])%m==0出发推导一下:
由等式(s[r]-s[l-1])%m==0显然有s[r]-s[l-1]=k*m,其中k为正整数。等式两边对m取模并变形得s[r]%m=(s[l-1]+k*m)%m=(s[l-1]%m+0)%m=(s[l-1]%m)%m,令t[r]=s[r]%m,t[l-1]=s[l-1]%m,得t[r]=t[l-1]%m。由取模运算的性质可知t[r]t[l-1]的范围都是[0,m-1],根据t[r]=t[l-1]%m一定有t[r]=t[l-1]。到这一步,题目就转化成了求相等的数有多少对(这一思路是在暴力枚举的基础上优化而来,因为用到了前缀和,所以要用上第0项0,输入的n个数从1开始到n,总共n+1个数。)考虑题目的数据范围,我们可以先排序,然后从0到n遍历并统计相同且个数大于1的数。

如果有更好的方法(二分?dp?等等)可以在评论中分享,谢谢!

#include<stdio.h>
#include<stdlib.h>
typedef long long int lli;
lli a[100005]={0};
int cmp(const void*a,const void*b)
{
    return *(lli*)a-*(lli*)b;
}
int main()
{
    int n;
    int m;
    int i;
    lli ans;
    lli temp;
    scanf("%d %d",&n,&m);
    for(i=1;i<=n;i++)
    {
        scanf("%lld",&a[i]);
    }
    for(i=1;i<=n;i++)//先求前缀和
    {
        a[i]+=a[i-1];
    }
    for(i=0;i<=n;i++)//再取模
    {
        a[i]=a[i]%m;
    }
    qsort(a,n+1,sizeof(a[0]),cmp);
    ans=0;
    temp=1;
    for(i=0;i<=n-1;i++)
    {
        if(a[i]==a[i+1])//统计相邻的数
        {
            temp++;
        }
        else
        {
            if(temp>=2)ans+=temp*(temp-1)/2;//n个数中选2个,共n*(n+1)/2种选法
            temp=1;
        }
    }
    if(temp>=2)ans+=temp*(temp-1)/2;
    printf("%lld",ans);
    return 0;
}
/**************************************************************
    Language: C++
    Result: 正确
    Time:36 ms
    Memory:2684 kb
****************************************************************/
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值