Blue Bridge Cup: 8th 10-question k times interval

Title: k times interval


Given a sequence of length N, A1, A2, ... AN, if the sum of a continuous subsequence Ai, Ai+1, ... Aj(i <= j) is K is a multiple of , we call this interval [i, j] a K times interval.  


Can you find the total number of K-fold intervals in the sequence?  


Input
-----
The first line contains two integers N and K. (1 <= N, K <= 100000)  
Each of the following N lines contains an integer Ai. (1 <= Ai <= 100000)  


Output
-----
Output an integer representing the number of K times the interval.  




For example,
input:
5 2
1  
2  
3  
4  
5   The


program should output:
6


Resource convention:
Peak memory consumption (including virtual machine) < 256M
CPU consumption < 2000ms




Please output strictly as required, do not superfluous print something like: "Please enter. .." is redundant.


Note: The
main function needs to return 0;
only use the ANSI C/ANSI C++ standard;
do not call special functions that depend on the compilation environment or operating system.
All dependent functions must be explicitly #include <xxx> in the source file
Common header files cannot be omitted through project settings.


提交程序时,注意选择所期望的语言类型和编译器类型。


解题思路:如果前i项和前j项和对K取余结果相同,那么i-j满足条件。 求数组前N项和,记录到一个数组sum中,记录取余相同的前N项和的个数,放在数组cnt中,结果就等于   cnt[i] * (cnt[i] - 1) / 2 (i = 0...).


#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;
int n, k;
int a[100010];
long long cnt[100010], sum[100010];//cnt[i]为前缀和取余后为i的个数,sum[i]计算前i项的和
int main()
{
    memset(sum, 0, sizeof(sum));
    memset(cnt, 0, sizeof(cnt));
    scanf("%d %d", &n, &k);
    for(int i = 1;i <= n;i++)
      scanf("%d", &a[i]), sum[i] = sum[i-1] + a[i];
    cnt[0] = 1;//注意0本身算一个起点
    for(int i = 1;i <= n;i++)
        cnt[sum[i]%k]++;
    long long ans = 0;
    for(int i = 0;i < k;i++)
        if(cnt[i])
        ans += (cnt[i]*(cnt[i]-1))/2;//C(n,2)
    printf("%lld", ans);
    return 0;
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324466904&siteId=291194637