加载中...

k倍区间

k倍区间

思路:前缀和 %k 后的余数相同的位置都是 k 倍区间

  1. 求前缀和
  2. 每一次求前缀和之后都 %k 并且记录余数的数量

image-20230329205104628

image-20230329205115725

import java.util.Scanner;

public class N97 {
	static int N = 10010;

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		int n = scanner.nextInt();
		int k = scanner.nextInt();
		int[] s = new int[N];
		int[] cnt = new int[N];
		s[0] = 0;
		cnt[0] = 1;
		for (int i = 1; i <= n; i++) {
			s[i] = scanner.nextInt();
			s[i] += s[i - 1];// 前 n 项和
			s[i] %= k;// %k 不影响下一次求和后再次 %k 的值
			cnt[s[i]]++;
		}
		long res = 0;
		for (int i = 0; i < k; i++) {
			res += cnt[i] * (cnt[i] - 1) / 2;// 组合数 Cn2
		}
		System.out.println(res);
	}

}

说明:

未 AC 求大佬告知,谢谢各位!

posted @ 2023-03-29 20:53  ChuenSan  阅读(20)  评论(0编辑  收藏  举报