junior19

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

1015. Letter-moving Game (35)

时间限制
200 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
CAO, Peng

Here is a simple intersting letter-moving game. The game starts with 2 strings S and T consist of lower case English letters. S and T contain the same letters but the orders might be different. In other words S can be obtained by shuffling letters in String T. At each step, you can move one arbitrary letter in S either to the beginning or to the end of it. How many steps at least to change S into T?

Input Specification:

Each input file contains one test case. For each case, the first line contains the string S, and the second line contains the string T. They consist of only the lower case English letters and S can be obtained by shuffling T's letters. The length of S is no larger than 1000.

Output Specification:

For each case, print in a line the least number of steps to change S into T in the game.

Sample Input:
iononmrogdg
goodmorning
Sample Output:
8
Sample Solution:
(0) starts from iononmrogdg
(1) Move the last g to the beginning: giononmrogd
(2) Move m to the end: giononrogdm
(3) Move the first o to the end: ginonrogdmo
(4) Move r to the end: ginonogdmor
(5) Move the first n to the end: gionogdmorn
(6) Move i to the end: gonogdmorni
(7) Move the first n to the end: googdmornin
(8) Move the second g to the end: goodmorning
可以转化为求最少移动几个字符,即几个字符不需要动,显然是求两个字符串的最长匹配,在S中为序列,在T中为子串,参考LCS的方程可得:

# include <stdio.h>
# include <string.h>
int max(int a, int b){return a>b?a:b;}
int dp[1008][1008];
int main()
{
    int len, i, j, imax;
    char s[1008], t[1008];
    while(~scanf("%s%s",s+1,t+1))
    {
        imax = -1;
        len = strlen(s+1);
        memset(dp, 0, sizeof(dp));
        for(i=1; i<=len; ++i)
            for(j=1; j<=len; ++j)
            {
                if(t[i]==s[j])
                    dp[i][j] = dp[i-1][j-1] + 1;
                else
                    dp[i][j] = dp[i][j-1];
                imax = max(imax, dp[i][j]);
            }
        printf("%d\n",len-imax);
    }
    return 0;
}



posted on 2017-01-20 22:14  junior19  阅读(153)  评论(0编辑  收藏  举报