1. 程式人生 > >51nod1472取餘最大值 分治

51nod1472取餘最大值 分治

Description 有一個長度為n的陣列a,現在要找一個長度至少為2的子段,求出這一子段的和,然後減去最大值,然後對k取餘結果為0。 問這樣的子段有多少個。

Sample Input 4 3 1 2 3 4

Sample Output 3

考慮分治, 對於最大值分情況討論一下即可。

#include <cstdio>
#include <cstring>

using namespace std;
typedef long long LL;
int _max(int x, int y) {return x > y ? x : y;}
int read() {
	int s = 0, f = 1; char ch = getchar();
	while(ch < '0' || ch > '9') {if(ch == '-') f = -1; ch =getchar();}
	while(ch >= '0' && ch <= '9') s = s * 10 + ch - '0', ch = getchar();
	return s * f;
}

int n, k, a[310000];
LL ans, s1[1100000], s2[1100000];

int gg(LL x) {return (x % k + k) % k;}

void solve(int l, int r) {
	if(l >= r) return ;
	int mid = (l + r) / 2;
	solve(l, mid);
	solve(mid + 1, r);
	LL maxx = 0, sum = 0;
	for(int i = mid; i >= l; i--) {
		sum += a[i], maxx = _max(maxx, a[i]);
		s1[gg(sum - maxx)]++;
	} LL cc = mid; maxx = 0, sum = 0; LL uu = 0, ii = 0;
	for(int i = mid + 1; i <= r; i++) {
		sum += a[i], maxx = _max(maxx, a[i]);
		while(a[cc] <= maxx && cc >= l) uu += a[cc], ii = _max(ii, a[cc]), cc--, s2[gg(uu)]++, s1[gg(uu - ii)]--;
		ans += s2[gg(k - (sum - maxx))];
		ans += s1[gg(k - sum)];
	} maxx = sum = 0;
	for(int i = mid; i >= l; i--) {
		sum += a[i], maxx = _max(maxx, a[i]);
		s1[gg(sum - maxx)] = 0; s2[gg(sum)] = 0;
	}
}

int main() {
	n = read(), k = read();
	for(int i = 1; i <= n; i++) a[i] = read();
	CDQ(1, n); printf("%lld\n", ans);
	return 0;
}