poj 3844 Divisible Subsequences(数学+抽屉原理)

来源:互联网 发布:传统企业转型网络案例 编辑:程序博客网 时间:2024/05/16 08:16

Language:
Divisible Subsequences
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 2596 Accepted: 946

Description

Given a sequence of positive integers, count all contiguous subsequences (sometimes called substrings, in contrast to subsequences, which may leave out elements) the sum of which is divisible by a given number. These subsequences may overlap. For example, the sequence (see sample input) 
2, 1, 2, 1, 1, 2, 1, 2

contains six contiguous subsequences the sum of which is divisible by four: the first to eighth number, the second to fourth number, the second to seventh number, the third to fifth number, the fourth to sixth number, and the fifth to seventh number.

Input

The first line of the input consists of an integer c (1 <= c <= 200), the number of test cases. Then follow two lines per test case. 
Each test case starts with a line consisting of two integers d (1 <= d <= 1 000 000) and n (1 <= n <= 50 000), the divisor of the sum of the subsequences and the length of the sequence, respectively. The second line of a test case contains the elements of the sequence, which are integers between 1 and 1 000 000 000, inclusively.

Output

For each test case, print a single line consisting of a single integer, the number of contiguous subsequences the sum of which is divisible by d.

Sample Input

27 31 2 34 82 1 2 1 1 2 1 2

Sample Output

06

 【题解】 一道很巧妙的数学题,求的是数组中连续子序列的和能整除m的序列的个数,我们可以输入时就把每个数mod要除的数,由数组保存,然后第二次白遍历,因为同一个余数之间的序列和一定能被m整除,所以遍历所有的余数,每次求得相同余数的个数n,C(n)(2)就是以这个相同余数为序列的序列个数,遍历所有的余数即可。

 【AC代码】

 

#include<iostream>#include<cstdio>#include<cmath>#include<cstring>#include<string>using namespace std;typedef long long ll;int c;ll d,n;ll num[1100000];int main(){    scanf("%d",&c);    while(c--)    {        ll ans=0;        ll m=0;        ll a;        memset(num,0,sizeof num);        scanf("%lld%lld",&d,&n);        for(int i=1;i<=n;i++)        {            scanf("%lld",&a);            m+=a;            ll p=m%d;            m%=d;            num[p]++;//余数保存        }        for(int i=0;i<d;i++)        {            if(!num[i])continue;//未用过            if(!i)            {                ans+=num[0];            }            ans+=num[i]*(num[i]-1)/2;//组合数学        }        printf("%lld\n",ans);    }    return 0;}