数组T[]
已用于存储所有可能的连续组合的总和。在每一步,我都在检查它是否至少为k
,并且该值存储在变量val
中。以下是Java代码:
import java.util.Arrays;
import java.util.Scanner;
class Codechef {
public static void main(String[] args) throws java.lang.Exception {
Scanner sc = new Scanner(System.in);
long t = sc.nextLong();
while (t > 0) {
int n = sc.nextInt();
long k = sc.nextLong();
long p = sc.nextLong();
long a[] = new long[n];
long T[] = new long[((n * (n + 1)) / 2)];
Arrays.fill(T, -1);
long sum = 0, x = 0, val = p, f = 0;
int i = 0;
for (i = 0; i < n; i++) {
a[i] = sc.nextLong();
sum = sum + a[i];
x = sum % p;
T[i] = x;
if (T[i] == k)
f = 1;
else if (T[i] > k && T[i] < val)
val = T[i];
}
if (f != 1) {
for (int j = i - 1; j > 0; j--) {
for (int m = 0; m < j; m++) {
x = T[j] - T[m];
if (x < 0)
x += p;
T[i] = x;
if (T[i] == k) {
f = 1;
break;
}
else if (T[i] > k && T[i] < val)
val = T[i];
i++;
}
if (f == 1)
break;
}
}
if (f == 1)
System.out.println(k);
else
System.out.println(val);
t--;
}
}
}
以上是SPOJ上PARTSUM- Partial Sums的代码。什么可能是错误?
之前我在提交时遇到运行时错误NZEC 。现在已经纠正,现在我正在 TLE 。任何优化?