P8649 [Lanqiao Cup 2017 Province B] k times interval (prefix sum + optimization (bucket classification))

analyze:

(1) Any continuous subsequence can be represented by the difference between the sum of two prefixes

(2) Determine whether the subsequence is a multiple of k p1-p2 modulo 0 (mod k)

Equivalent to: whether the prefix sum modulo k is congruent

(3) The sequence of any two prefix sum combinations of congruence satisfies the multiple of k

(4) Those with a remainder of 0 require special judgment, because the prefix sum with a remainder of 0 itself also meets the conditions

accomplish:

1. Use the rolling window to calculate the results of the prefix sum modulo k one by one,

2. Use the bucket array to count the number of different remainders modulo k. 

#include<iostream>
using namespace std;

long long count1[1000009] = {0};

int main()
{
	int n, k; cin >> n >> k;
	long long ans = 0,sum=0;
	for (int i = 0; i < n; i++)
	{
		long long temp = 0;
		scanf("%lld", &temp);
		sum = (sum + temp) % k;
		count1[sum]++;
	}
	// 单一前缀和为k的倍数(特判)
	ans += (count1[0] * (count1[0] + 1) / 2);

	for (int i = 1; i < k; i++)
		// 单一前缀和不为k的倍数
		ans += (count1[i] * (count1[i] - 1) / 2);
	

	cout << ans;
	return 0;
}

Guess you like

Origin blog.csdn.net/2301_79140115/article/details/134690668
Recommended