2017第八届蓝桥杯 K倍区间

标题: k倍区间
给定一个长度为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

思路:如果两个数x和y对k求余的值相同,那么abs(x - y) % k == 0,首先O(n)预处理,dp(i)表示前i个数的和。


详细代码:

#include <cstdio>
#include <cmath>
#include <cctype>
#include <algorithm>
#include <cstring>
#include <utility>
#include <string>
#include <iostream>
#include <map>
#include <set>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
#pragma comment(linker, "/STACK:1024000000,1024000000") 
#define eps 1e-10
#define inf 0x3f3f3f3f
#define PI pair<int, int> 
typedef long long LL;
const int maxn = 1e6 + 5;
int cnt[maxn];
LL sum[maxn];
int main() {
	int n, k;
	while(scanf("%d%d", &n, &k) == 2) {
		int val;
		sum[0] = 0;
		for(int i = 1; i <= n; ++i) {
			scanf("%d", &val);
			sum[i] = sum[i-1] + val;
		}
		memset(cnt, 0, sizeof(cnt));
		cnt[0] = 1; //区间(0, i)的和为k的倍数 
		for(int i = 1; i <= n; ++i) {
			cnt[sum[i] % k]++;
		}
		LL ans = 0;
		for(int i = 0; i < k; ++i) {
			if(cnt[i])
				ans += (LL)cnt[i] * (cnt[i]-1) / 2; //任选两个作为区间的上下界
		}
		printf("%lld\n", ans);
	}
	return 0;
} 

如有不当之处欢迎指出!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值