1. 程式人生 > >演算法導論第十五章(最長公共子序列)

演算法導論第十五章(最長公共子序列)

package chapter15_dynamic_programming;

import java.util.ArrayList;

/**
 * 動態規劃:最長公共子序列,動態規劃的演算法自底向上的計算
 * 
 * @author liuyw
 *
 */

public class LCSLength {

	public static String[] arr = new String[1000];

	public static int zz = 0;
	public static int count = 0;

	public static void main(String[] args) {

		// Scanner sc = new Scanner(System.in);
		// int k = sc.nextInt();
		// int[] x1 = new int[k + 1];
		// x1[0] = 0;
		// for (int i = 1; i < x1.length; i++) {
		// x1[i] = sc.nextInt();
		// }
		//
		// int[] y1 = x1.clone();
		// Arrays.sort(y1);

		int[] x1 = { ' ', 10, 4, 5, 12, 8 };
		int[] y1 = { ' ', 4, 5, 6, 7, 8, 9, 10, 11, 12 };

		int m = x1.length;
		int n = y1.length;

		int[][] c = new int[m][n];// 初始化全部為零
		int[][] b = new int[m][n];

		ArrayList<Character> result = new ArrayList<Character>();

		LCSLengthFunction(x1, y1, c, b, m, n);// 構造出帶箭頭的表

		LCS(m - 1, n - 1, x1, b, result);
		// for (char tm : result) {
		// System.out.println("*" + tm);
		// }

		System.out.println(count);
	}

	private static void LCSLengthFunction(int[] x1, int[] y1, int[][] c,
			int[][] b, int m, int n) {
		/*
		 * for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { c[i][j] =
		 * 0; } }
		 */
		// m:x1長度,n:x2長度
		for (int i = 1; i < m; i++) {
			for (int j = 1; j < n; j++) {
				if (x1[i] == y1[j]) {
					c[i][j] = c[i - 1][j - 1] + 1;
					b[i][j] = 1;
				} else if (c[i - 1][j] >= c[i][j - 1]) {
					c[i][j] = c[i - 1][j];
					b[i][j] = 2;

				} else {
					c[i][j] = c[i][j - 1];
					b[i][j] = 3;
				}
			}
		}
	}

	private static void LCS(int i, int j, int[] x1, int[][] b,
			ArrayList<Character> result) {

		if (i == 0 || j == 0)
			return;
		if (b[i][j] == 1) {
			result.add((char) x1[i]);
			LCS(i - 1, j - 1, x1, b, result);
			count++;
			System.out.println(x1[i]);
		} else if (b[i][j] == 2) {
			result.add('2');
			LCS(i - 1, j, x1, b, result);
			// System.out.println("2");
		} else {
			result.add('3');
			LCS(i, j - 1, x1, b, result);
			// System.out.println("3");
		}

	}

}