2016年8月28日星期日

Shortest Common Supersequence

Problem
   Given two strings str1 and str2, find the shortest string that has both str1 and str2 as subsequences.

Solution
   str1len + str2len - lcs

Code
#include <stdio.h>
#include <iostream>
using namespace std;
const int N = 110;
int dp[N][N];
string a,b;
int main() {
    cin >> a >> b;
 int n = a.size();
 int m = b.size();
 dp[0][0] = 0;
 for (int i = 1;i <= n;i ++) {
     for (int j = 1;j <= m;j ++) {
         if (a[i] == b[j]) {
             dp[i][j] = dp[i - 1][j - 1] + 1;
         }
         else {
             dp[i][j] = max(dp[i][j - 1],dp[i - 1][j]);
         }
     }
 }
 cout << n + m - dp[n][m] << endl;
 return 0;
}

没有评论:

发表评论