0-1背包
public class Knapsack {
public static void main(String[] args) {
int[] w = {2,2,6,5,4};
int[] v = {3,6,5,4,6};
int most_w = 10;
System.out.print("各个物品重量为:");
for (int i: w)
System.out.print(i + " ");
System.out.println();
System.out.print("各个物品的价值为:");
for (int i: v)
System.out.print(i + " ");
System.out.println();
System.out.println("背包最大容量为:"+most_w);
knapsack(w, v, most_w);
}
public static void knapsack(int[] w, int[] v, int most_w) {
int n = w.length;
int[][] c = new int[n+1][most_w+1];
for (int i=1; i<=n; i++) {
for (int j=1; j<=most_w; j++) {
int weight = w[i-1];
int value = v[i-1];
if (weight <= j)
c[i][j] = Math.max(c[i-1][j], c[i-1][j-weight]+value);
else
c[i][j] = c[i-1][j];
}
}
System.out.println("最大价值为:"+ c[n][most_w]);
int[] x = new int[n];
int j = most_w;
for (int i=x.length; i>0; i--) {
if (c[i][j] > c[i-1][j]) {
x[i-1] = 1;
j -= w[i-1];
}
}
System.out.print("最优解为:");
for (int i: x)
System.out.print(i + " ");
}
}
最长公共子序列
public class LCS {
public static void main(String[] args) {
String x = "ABCBDAB";
String y = "BDCABA";
int m = x.length();
int n = y.length();
int[][] c = new int[m+1][n+1];
int[][] b = new int[m+1][n+1];
for (int i=0; i<=n; i++) {
c[0][i] = 0;
b[0][i] = 0;
}
for (int i=0; i<=m; i++) {
c[i][0] = 0;
b[i][0] = 0;
}
System.out.println("字符串1:" + x);
System.out.println("字符串2:" + y);
LCSlength(m, n, x, y, c, b);
System.out.println("x,y 的最长公共子序列长度为:" + c[m][n]);
System.out.println("倒序输出 公共子序列:");
LCS(m, n, b, x);
}
public static void LCSlength(int m, int n, String x, String y, int[][] c, int[][] b) {
for (int i=1; i<=m; i++) {
for (int j=1; j<=n; j++) {
if (x.charAt(i-1) == y.charAt(j-1)) {
c[i][j] = c[i-1][j-1] + 1;
b[i][j] = 1;
} else if (c[i][j-1] > c[i-1][j]) {
c[i][j] = c[i][j-1];
b[i][j] = 2;
} else {
c[i][j] = c[i-1][j];
b[i][j] = 3;
}
}
}
System.out.println("输出所填动归表:");
for (int i=0; i<=m; i++) {
for (int j=0; j<=n; j++) {
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
public static void LCS(int i, int j, int[][] b, String x) {
if (i==0 || j==0) {
return;
}
if (b[i][j] == 1) {
System.out.print(x.charAt(i-1) + " ");
LCS(i-1, j-1, b, x);
} else if (b[i][j] == 2) {
LCS(i, j-1, b, x);
} else {
LCS(i-1, j, b, x);
}
}
}