HDU 1503 Advanced Fruits
hdu : http://acm.hdu.edu.cn/showproblem.php?pid=1503
题意:
两种水果杂交出一种新水果,现在给新水果取名,要求这个名字中包含了以前两种水果名字的字母,并且这个名字要尽量短。也就是说以前的一种水果名字x是新水果名字s的子序列,另一种水果名字y也是新水果名字s的子序列。要你求s。
做法:
用求最长公共子序列的方法,求出x和y的最长公共子序列,然后再用递归思想,逐一输出,得到的就是最后答案。
代码:
View Code
1 #include<stdio.h> 2 #include<string.h> 3 int c[1010][1010],b[105][105],n,m,k; 4 char s[1010],x[1010],y[1010]; 5 //输出时利用递归思想输出; 6 void printLCS(int i,int j) 7 { 8 if(i==0&&j==0) 9 return; 10 if(i==0) 11 { 12 printLCS(i,j-1); 13 printf("%c",y[j-1]);//输出x,y时下标要减1,因为在记b(方向)的时候是从1开始的; 14 return; 15 } 16 else if(j==0) 17 { 18 printLCS(i-1,j); 19 printf("%c",x[i-1]); 20 return; 21 } 22 if(b[i][j]==0) 23 { 24 printLCS(i-1,j-1); 25 printf("%c",x[i-1]); 26 } 27 else if(b[i][j]==1) 28 { 29 printLCS(i-1,j); 30 printf("%c",x[i-1]); 31 } 32 else 33 { 34 printLCS(i,j-1); 35 printf("%c",y[j-1]); 36 } 37 } 38 void LCS() 39 { 40 int i,j; 41 for(i=0;i<n;i++) 42 c[i][0]=0; 43 for(j=1;j<m;j++) 44 c[0][j]=0; 45 for(i=1;i<=n;i++) 46 for(j=1;j<=m;j++) 47 { 48 if(x[i-1]==y[j-1]) 49 { 50 c[i][j]=c[i-1][j-1]+1; 51 b[i][j]=0; 52 } 53 else if(c[i-1][j]>c[i][j-1]) 54 { 55 c[i][j]=c[i-1][j]; 56 b[i][j]=1; 57 } 58 else 59 { 60 c[i][j]=c[i][j-1]; 61 b[i][j]=2; 62 } 63 } 64 printLCS(n,m); 65 puts(""); 66 } 67 int main() 68 { 69 int i,j; 70 while(~scanf("%s %s",x,y)) 71 { 72 memset(b,-1,sizeof(b)); 73 n=strlen(x); 74 m=strlen(y); 75 LCS(); 76 } 77 return 0; 78 }
posted on 2012-08-15 17:07 acoderworld 阅读(439) 评论(0) 收藏 举报

浙公网安备 33010602011771号