标题: 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
暴力
可以过两个:
public class K倍区间 {
// 暴力过不了
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
int cnt = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = i; j < arr.length; j++) {
if (func(arr, i, j) % k == 0) {
cnt++;
}
}
}
System.out.println(cnt);
}
public static int func(int[] arr, int i, int j) {
int sum = 0;
while (i <= j) {
sum += arr[i];
i++;
}
return sum;
}
}
前缀和
前缀和在这里也只能过两个。。
public class K倍 {
// 就是先计数,然后计算同样余数的数字中选择其中两个出来的组合数
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int N = in.nextInt();
int K = in.nextInt();
int[] nums = new int[N + 1];
long[] cnt = new long[nums.length];
for (int i = 1; i <= N; i++) {
nums[i] = in.nextInt();
cnt[i] = cnt[i - 1] + nums[i];// 前缀和
}
int res = 0;
for (int i = 1; i <cnt.length; i++) {
for (int j = i; j < cnt.length; j++) {
if ((cnt[j] - cnt[i - 1]) % K == 0) {
res++;
}
}
}
System.out.println(res);
}
}
所以必须进行优化,优化呢,就要用到数学知识——组合数学
长见识了,但是我是不可能想出来的!
优化
public class K倍区间2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int[] arr = new int[n + 1];
long[] count = new long[arr.length];
// 前缀和数组
long[] prefix = new long[arr.length];
prefix[0] = 0;
count[0] = 1;
for (int i = 1; i <= n; i++) {
arr[i] = sc.nextInt();
prefix[i] = (arr[i] + prefix[i - 1]) % k;
count[(int) prefix[i]]++;
}
long cnt = 0;
for (int i = 0; i < k; i++) {
cnt += (long) (count[i] * (count[i] - 1) / 2); // 万事小心
}
System.out.println(cnt);
}
}
我犯了很多次这个错误:
- cnt[j] - cnt[i - 1] % K == 0,这里一直有错,我要求的是cnt[ j ] -cnt[ i - 1]的差对k取模,可是为什么总是错的呢?
- 原因在于!!!——%的优先级> -的优先级!所以一定要加括号!加括号
另外, count[i] * count[i] - 1 / 2,这里我也犯了错,没有加括号!!思路不清晰!
注意细节!!思路要正确!!!
end.