您的位置:首页 > 其它

动态规划算法,最小代价

2015-06-22 16:19 190 查看
<span style="color: rgb(51, 51, 51); font-family: Helvetica, Tahoma, Arial, sans-serif; font-size: 14px; line-height: 24px; background-color: rgb(245, 245, 245);">将一个字符串通过插入字符串或者删除字符串的方式转换为另一个给定的字符串。删除连续n个字符的操作的代价为2,插入n个字符的代价为n+2。求转换的最小代价。</span>
<span style="color: rgb(51, 51, 51); font-family: Helvetica, Tahoma, Arial, sans-serif; font-size: 14px; line-height: 24px; background-color: rgb(245, 245, 245);">
</span>
package com.test;

import com.copy.test.Demo1CopyTest;

public class Demo {

	public static void main(String[] args) {
		GetMinExpenses("AABB", "BB");
	}

	public static int DEL = -1;

	public static int ORIGAL = 0;

	public static int ADD = 1;

	public static int getAddCount(int f, int type) {
		int minCost;
		if (type == ADD) {
			minCost = f + 1;
		} else {
			minCost = f + 3;
		}
		return minCost;
	}

	public static int getDelCount(int f, int type) {
		int minCost = 0;
		if (type == DEL) {
			minCost = f + 0;
		} else {
			minCost = f + 2;
		}
		return minCost;
	}

	public static int getMin(int a, int b) {
		return a < b ? a : b;
	}

	public static int GetMinExpenses(String aString, String bString) {
		int[][] f = new int[aString.length() + 1][bString.length() + 1];//f[i][j] 从a[i] -> b[j]的最小代价
		f[0][0] = 0;
		int operator[][] = new int[aString.length() + 1][bString.length() + 1];//用于记录操作

		for (int i = 1; i < aString.length() + 1; i++) {
			f[i][0] = 2;
			operator[i][0] = DEL;
		}
		for (int i = 1; i < bString.length() + 1; i++) {
			f[0][i] = 2 + i;
			operator[0][i] = ADD;
		}
		int type = ORIGAL;
		for (int i = 1; i < aString.length() + 1; i++) {
			// System.out.println();
			for (int j = 1; j < bString.length() + 1; j++) {
				// System.out.print(minCost + "_" + operator[i][j] + " ");
				int tempType;
                int cost = 0;
                if (aString.charAt(i - 1) != bString.charAt(j - 1))
                {
                    cost = 5;
                }
                int minCost;
                int delCount = getDelCount(f[i - 1][j], operator[i - 1][j]);
                int addCount = getAddCount(f[i][j - 1], operator[i][j - 1]);
                if (delCount >= addCount)
                {
                    operator[i][j] = ADD;
                    minCost = addCount;
                }
                else
                {
                    operator[i][j] = DEL;
                    minCost = delCount;
                }
                if (minCost > f[i - 1][j - 1] + cost)
                {
                    operator[i][j] = ORIGAL;
                    minCost = f[i - 1][j - 1] + cost;
                }
                f[i][j] = minCost;
			}
			// System.out.println("");
		}
		return f[aString.length()][bString.length()];
	}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: