题目大意:给定一个数和一个序列 计算这个序列中有多少个子序列的和是这个数的倍数。
思路:a[i]+a[i+1]+..+a[j] = s[j]-s[i],如果要和是其倍数, 则表示s[j]-s[i]能够整除那个数,只要s[j]和s[i]对那个数的余数相同就可以了啊,所以,将各个和按余数分堆!! 每个堆选择两个出来,即(n*n-1)/2;
ps: 余数分堆很常用!! 序列为两个相减也很常用!!
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 subse-quences 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
#include<iostream>
#include<cstring>
using namespace std;
const int num=1000010;
int sum[50010],divd[num];
int main()
{
int c,d,n,a;
cin>>c;
while(c--)
{
cin>>d>>n;
sum[0]=0;
for(int i=0;i<n;i++)
{
cin>>a;
sum[i+1]=(sum[i]+a)%d;
}
memset(divd,0,sizeof(divd));
for(int i=0;i<=n;i++)
{
divd[sum[i]]++;
}
long long count=0;
for(int i=0;i<d;i++)
{
if(divd[i]>=2)
count=count+(long long)divd[i]*(divd[i]-1)/2;
}
cout<<count<<endl;
}
return 0;
}
本文介绍了一种算法,用于计算给定序列中子序列之和为特定数倍数的总数。通过余数分堆的方法,可以有效解决此类问题。
741

被折叠的 条评论
为什么被折叠?



