给定一个长度为N的数列,A1, A2, ... AN,如果其中一段连续的子序列Ai, Ai+1, ... Aj(i <= j)之和是K的倍数,我们就称这个区间[i, j]是K倍区间。
你能求出数列中总共有多少个K倍区间吗?
输入
-----
第一行包含两个整数N和K。(1 <= N, K <= 100000)
以下N行每行包含一个整数Ai。(1 <= Ai <= 100000)
输出
-----
输出一个整数,代表K倍区间的数目。
例如,
输入:
5 2
1
2
3
4
5
程序应该输出:
6
资源约定:
峰值内存消耗(含虚拟机) < 256M
CPU消耗 < 2000ms
请严格按要求输出,不要画蛇添足地打印类似:“请您输入...” 的多余内容。
注意:
main函数需要返回0;
只使用ANSI C/ANSI C++ 标准;
不要调用依赖于编译环境或操作系统的特殊函数。
所有依赖的函数必须明确地在源文件中 #include <xxx>
不能通过工程设置而省略常用头文件。
你能求出数列中总共有多少个K倍区间吗?
输入
-----
第一行包含两个整数N和K。(1 <= N, K <= 100000)
以下N行每行包含一个整数Ai。(1 <= Ai <= 100000)
输出
-----
输出一个整数,代表K倍区间的数目。
例如,
输入:
5 2
1
2
3
4
5
程序应该输出:
6
资源约定:
峰值内存消耗(含虚拟机) < 256M
CPU消耗 < 2000ms
请严格按要求输出,不要画蛇添足地打印类似:“请您输入...” 的多余内容。
注意:
main函数需要返回0;
只使用ANSI C/ANSI C++ 标准;
不要调用依赖于编译环境或操作系统的特殊函数。
所有依赖的函数必须明确地在源文件中 #include <xxx>
不能通过工程设置而省略常用头文件。
提交程序时,注意选择所期望的语言类型和编译器类型。
思路:计算前缀和s[0], s[1], s[2], … s[N]。统计s[]中模K余0, 1, 2 … K-1的数量,记为cnt[0], cnt[1], cnt[2] … cnt[K-1]。答案就是:cnt[0]*(cnt[0]-1)/2 + cnt[1]*(cnt[1]-1)/2 +… +cnt[K-1]*(cnt[K-1]-1)/2。
#include <algorithm>
#include <string>
#include <iostream>
#include <stdio.h>
#include <string>
#include <vector>
#include <queue>
#include <map>
#include <set>
#include<stack>
#include<cmath>
#include<cstdio>
#include<bitset>
#include<iomanip>
#include<cstring>
#include<functional>
using namespace std;
const int MAXN = 100010;
int arr[MAXN];
long long s[MAXN] = {0};
int cnt[MAXN] = {0};
int main(){
int n,k;
scanf("%d%d",&n,&k);
for(int i = 1;i <= n;i++){
scanf("%d",&arr[i]);
}
long long ans = 0;
cnt[0] = 1;
for(int i = 1;i <= n;i++){
s[i] = (s[i-1]+arr[i])%k;
cnt[s[i]]++;
}
for(int i = 0;i < k;i++){
ans += (long long)(cnt[i])*(cnt[i]-1)/2;
}
printf("%lld\n",ans);
return 0;
}