解题思路
如果使用了先走和后走的方式,这种方式利用了贪心的思想,会产生局部最优解,
但局部最优解毕竟不是全局最优解。所以要采用同时走的方式。
相关代码
import java.util.Scanner;public class Main {static int w[][] = new int[15][15];static int f[][][] = new int[30][15][15];public static void main(String[] args){Scanner scan = new Scanner(System.in);int n = scan.nextInt();while(true){int a = scan.nextInt();int b = scan.nextInt();int c = scan.nextInt();if(a==0&&b==0&&c==0) break;w[a][b] = c;}for(int k=2;k<=2*n;k++){for(int i1=1;i1<=n;i1++){for(int i2=1;i2<=n;i2++){int j1 = k-i1;int j2 = k-i2;if(j1<0||j2<0) continue;int t = w[i1][j1];if(i1!=i2) t+=w[i2][j2];int x = f[k][i1][i2];x = Math.max(x,f[k-1][i1-1][i2-1]+t);x = Math.max(x,f[k-1][i1-1][i2]+t);x = Math.max(x,f[k-1][i1][i2-1]+t);x = Math.max(x,f[k-1][i1][i2]+t);f[k][i1][i2] = x;}}}System.out.println(f[2*n][n][n]);}
}