Divisible Subsequences
Time Limit: 1000MS | Memory Limit: 65536K | |
Total 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.
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.
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
2 7 3 1 2 3 4 8 2 1 2 1 1 2 1 2
Sample Output
0 6
Source
题意:给一个长度为n的序列,为有多少个区间使得区间和能整除m
如果区间[x,y]的和能整除一个数,那么[1,x]的和%m一定和[1,y]的和%m相等,可以先计算一遍[1,y]所有数的和%m,用数组将余数保存起来,最后计算余数情况即可
假设从[1,x]余数为1的的数有l个,那么满足条件的区间数就为C(l,2),当余数为0的时候要特殊处理一下,因为可以直接从1到x,即只有一个余数为0的x也能构成区间
#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)//余数为0的可以自己构成一个区间
{
ans+=num[0];
}
ans+=num[i]*(num[i]-1)/2;//两个num相乘可能爆int
}
printf("%lld\n",ans);
}
return 0;
}