Time Limit: 2000MS | Memory Limit: 32768KB | 64bit IO Format: %lld & %llu |
Description
You are given an array with N integers, and another integer M. You have to find the number of consecutive subsequences which are divisible by M.
For example, let N = 4, the array contains {2, 1, 4, 3} and M = 4.
The consecutive subsequences are {2}, {2 1}, {2 1 4}, {2 1 4 3}, {1}, {1 4}, {1 4 3}, {4}, {4 3} and {3}. Of these 10 'consecutive subsequences', only two of them adds up to a figure that is a multiple of 4 - {1 4 3} and {4}.
Input
Input starts with an integer T (≤ 10), denoting the number of test cases.
Each case contains two integers N (1 ≤ N ≤ 105) and M (1 ≤ M ≤ 105). The next line contains N space separated integers forming the array. Each of these integers will lie in the range [1, 105].
Output
For each case, print the case number and the total number of consecutive subsequences that are divisible by M.
Sample Input
2
4 4
2 1 4 3
6 3
1 2 3 4 5 6
Sample Output
Case 1: 2
Case 2: 11
Hint
解题思路:设dp[i]为余数为i的前缀和出现了几次,如果两次前缀和的余数相等了,表示中间所加的数刚好是k的倍数了,这就可以抽离出来了,将其分成段,再取, 方法很巧妙,需要领会
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int N = 100010;
int dp[N];
int main()
{
int ncase=1, t, n, m;
scanf("%d", &t);
while(t--)
{
scanf("%d %d", &n, &m);
memset(dp,0,sizeof(dp));
int sum=0;
long long ans=0;
dp[0]=1;
for(int i=0;i<n;i++)
{
int x;
scanf("%d", &x);
sum=(sum+x)%m;
ans+=dp[sum];
dp[sum]++;
}
printf("Case %d: %lld\n",ncase++, ans);
}
return 0;
}