用C++完成题目描述 Given are a sequence of N positive integers A1,A2,…,AN, and a positive integer K. Find the number of non-empty contiguous subsequences in A such that the remainder when dividing the sum of its elements by K is equal to the number of its elements. We consider two subsequences different if they are taken from different positions, even if they are equal sequences. Constraints ·All values in input are integers. ·1≤N≤2×105 ·1≤K≤109 ·1≤Ai≤109 输入 Input is given from Standard Input in the following format: N K A1 A2 ⋯ AN 输出 Print the number of subsequences that satisfy the condition.
时间: 2023-06-09 12:04:13 浏览: 178
好的,我理解了你的问题。这是一个经典的数学问题,可以使用C语言来解决。下面是我提供的一个C语言解决方案:
```c
#include<stdio.h>
#define ll long long
#define MAXN 200005
int n, k;
int a[MAXN];
int pre[MAXN];
ll cnt[MAXN];
int main() {
scanf("%d%d", &n, &k);
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
pre[i] = (pre[i - 1] + a[i]) % k;
cnt[pre[i]]++;
}
ll ans = 0;
for (int i = 0; i < k; i++) {
ans += cnt[i] * (cnt[i] - 1) / 2;
}
printf("%lld\n", ans);
return 0;
}
```
这个程序的思路如下:
首先将输入的序列进行预处理,计算它的前缀和,并对它们做模K的运算。
然后,我们用一个数组cnt记录每个余数出现的次数。由于我们只需要计算满足条件的子序列数目,因此可以用cnt[i]中的余数为i的数目计算出余数为i的子序列的数量。
最后,我们用一个变量ans累加所有余数为i的子序列的数量,其中i的取值范围为[0,k)。由于一个子序列可能满足多个余数的条件,因此需要将满足某个余数的子序列数量两两配对,最后除以2。这里的配对是通过n(n-1)/2计算的,n为余数为i的子序列的数量。
希望这个答案对你有所帮助。
阅读全文
相关推荐















