Advanced Fruits (POJ - 2264)
题面
The company “21st Century Fruits” has specialized in creating new sorts of fruits by transferring genes from one fruit into the genome of another one. Most times this method doesn’t work, but sometimes, in very rare cases, a new fruit emerges that tastes like a mixture between both of them.
A big topic of discussion inside the company is “How should the new creations be called?” A mixture between an apple and a pear could be called an apple-pear, of course, but this doesn’t sound very interesting. The boss finally decides to use the shortest string that contains both names of the original fruits as sub-strings as the new name. For instance, “applear” contains “apple” and “pear” (APPLEar and apPlEAR), and there is no shorter string that has the same property. A combination of a cranberry and a boysenberry would therefore be called a “boysecranberry” or a “craboysenberry”, for example.
Your job is to write a program that computes such a shortest name for a combination of two given fruits. Your algorithm should be efficient, otherwise it is unlikely that it will execute in the alloted time for long fruit names.
输入
Each line of the input contains two strings that represent the names of the fruits that should be combined. All names have a maximum length of 100 and only consist of alphabetic characters. Input is terminated by end of file.
输出
For each test case, output the shortest name of the resulting fruit on one line. If more than one shortest name is possible, any one is acceptable.
样例输入
1apple peach
2ananas banana
3pear peach
样例输出
1appleach
2bananas
3pearch
提示
无
思路
代码
1using namespace std;
2typedef long long ll;
3const int inf = 0x3f3f3f3f;
4const int N = 1e2+5;
5
6string s, t;
7int dp[N][N];
8
9void print(int i, int j) {
10 stack<char>st;
11 while(i||j) {
12 if(i==0) {
13 st.push(t[j-1]), j--;
14 continue;
15 }
16 if(j==0) {
17 st.push(s[i-1]), i--;
18 continue;
19 }
20 if(s[i-1]==t[j-1]) {
21 st.push(s[i-1]);
22 i--, j--;
23 } else {
24 if(dp[i-1][j]>dp[i][j-1])
25 st.push(s[i-1]), i--;
26 else
27 st.push(t[j-1]), j--;
28 }
29 }
30 while(st.size()) {
31 cout<<st.top();
32 st.pop();
33 }
34 cout<<endl;
35}
36
37int main(void) {
38 while(cin>>s>>t) {
39 int n = s.size();
40 int m = t.size();
41 memset(dp, 0, sizeof(dp));
42 for(int i=1; i<=n; i++) {
43 for(int j=1; j<=m; j++) {
44 if(s[i-1]==t[j-1])
45 dp[i][j] = dp[i-1][j-1]+1;
46 else
47 dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
48 }
49 }
50 print(n, m);
51 }
52 return 0;
53}