递归,时间复杂度过大
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for(int i = 0; i < T; ++i){
int n = sc.nextInt();
int[] a = new int[n];
for(int j = 0; j < n; ++j){
a[j] = sc.nextInt();
}
int[] res = funCore(a, 0, a.length - 1);
int A = res[0];
int B = res[1] - res[0];
System.out.printf("Case #%d:%d %d\r\n", i + 1, A, B);
}
}
public static int[] funCore(int[] a, int b, int e){
if(b == e)
return new int[]{a[b], a[b]};
int[] l = funCore(a, b, e - 1);
int[] r = funCore(a, b + 1, e);
int sum = l[1] + a[e];
int l_r = Math.min(l[0], r[0]);
return new int[]{sum - l_r, sum};
}
}
将递归改程dp矩阵,程序通过。貌似大部分动态规划都是矩阵的时间复杂度低于递归的时间复杂度
这种情况是因为我System.out.printf()中的冒号后面少了一个空格(下面的代码就是少了一个空格)。加了空格之后就好了
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for(int i = 0; i < T; ++i){
int n = sc.nextInt();
int[] a = new int[n];
for(int j = 0; j < n; ++j){
a[j] = sc.nextInt();
}
int[] res = fun(a);
int A = res[0];
int B = res[1] - res[0];
System.out.printf("Case #%d:%d %d\r\n", i + 1, A, B);
}
}
public static int[] fun(int[] a){
int len_a = a.length;
int[][][] dp = new int[len_a][len_a][2];
for(int i = 0; i < len_a; ++i){
for(int j = 0; j < len_a; ++j){
int x = j;
int y = x + i;
if(y >= len_a)break;
if(x == y){
dp[x][y][0] = a[x];
dp[x][y][1] = a[x];
}else{
int sum = dp[x][y - 1][1] + a[y];
int min = Math.min(dp[x][y - 1][0], dp[x + 1][y][0]);
dp[x][y][0] = sum - min;
dp[x][y][1] = sum;
}
}
}
return dp[0][len_a - 1];
}
}