输出三行,第一行和第二行均为一行字符串,分别表示两个字符串str1,str2。。第三行为三个正整数,代表ic,dc和rc。(1<=ic<=10000、1<=dc<=10000、1<=rc<=10000)
输出一个整数,表示编辑的最小代价。
abc adc 5 3 2
2
abc adc 5 3 100
8
abc abc 5 3 2
0
时间复杂度,空间复杂度。(n,m代表两个字符串长度)
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { String str1 = sc.nextLine().trim(); String str2 = sc.nextLine().trim(); String[] s = sc.nextLine().trim().split(" "); int ic=Integer.parseInt(s[0]); int dc=Integer.parseInt(s[1]); int rc=Integer.parseInt(s[2]); int res=new Solution().getMinCost(str1,str2,ic,dc,rc); System.out.println(res); } } } class Solution { public int getMinCost(String str1,String str2,int ic,int dc,int rc){ int[][] dp=new int[str1.length()][str2.length()]; boolean flag=false; for (int i = 0; i < str1.length(); i++) { if(!flag&&str1.charAt(i)==str2.charAt(0)) flag=true; if(flag){ dp[i][0]=i*dc; }else{ dp[i][0]=Math.min(i*dc+rc,(i+1)*dc+ic); } } flag=false; for (int i = 0; i < str2.length(); i++) { if(!flag&&str2.charAt(i)==str1.charAt(0)) flag=true; if(flag){ dp[0][i]=i*ic; }else{ dp[0][i]=Math.min(i*ic+rc,(i+1)*ic+dc); } } for (int i = 1; i < str1.length(); i++) { for (int j = 1; j < str2.length(); j++) { if(str1.charAt(i)==str2.charAt(j)){ dp[i][j]=dp[i-1][j-1]; }else{ dp[i][j]=Math.min(dp[i-1][j]+dc,dp[i][j-1]+ic); dp[i][j]=Math.min(dp[i][j],dp[i-1][j-1]+rc); dp[i][j]=Math.min(dp[i][j],dp[i-1][j-1]+ic+dc); } } } return dp[str1.length()-1][str2.length()-1]; } }
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str1 = sc.nextLine(); String str2 = sc.nextLine(); int ic = sc.nextInt(); int dc = sc.nextInt(); int rc = sc.nextInt(); System.out.println(minCount(str1, str2, ic, dc, rc)); } public static int minCount(String str1, String str2, int ic, int dc, int rc) { int len1 = str1.length(); int len2 = str2.length(); int[][] dp = new int[len1 + 1][len2 + 1]; dp[0][0] = 0; for (int j = 1; j <= len2; j++) { dp[0][j] = j * ic; } for (int i = 1; i <= len1; i++) { dp[i][0] = i * dc; } for (int i = 1; i <= len1; i++) { for (int j = 1; j <= len2; j++) { if (str1.charAt(i - 1) == str2.charAt(j - 1)) dp[i][j] = dp[i - 1][j - 1]; else dp[i][j] = min(dp[i - 1][j - 1] + rc, dp[i - 1][j] + dc, dp[i][j - 1] + ic); } } return dp[len1][len2]; } public static int min(int a, int b, int c) { int temp = a; if (b < temp) temp = b; if (c < temp) temp = c; return temp; } }