1015 Letter-moving Game (35 分)(C++)

PAT頂級題解目錄​​​​​​​

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

題目大意:給出兩個序列,保證兩個序列的組成(字符)相同,現在問要將序列2變爲序列1需要幾步?

解題思路:其實題目的意思就是求兩個字符串的最長公共子序列。我們要將word2恢復到word1的狀態,要找到word2與word1最長公共子序列,可以用暴力搜索,最後用word1的長度減去公共子序列的長度就可以了。

代碼:

#include<bits/stdc++.h>
using namespace std;
int main(){
    string word1, word2;
    cin >> word1 >> word2;
    int m = 0;
    for(int i = 0; i < word2.length(); ++ i){
        int k = 0, j = i;
        for(char c : word1)
            if(word2[j] == c){
                ++ j;
                ++ k;
            }
        m = max(m, k);
    }
    printf("%d", word1.length()-m); 
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章