HDU4545+LCS
最长公共子序列。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /* 2 LCS 最长公共子序列 3 */ 4 #include<stdio.h> 5 #include<string.h> 6 #include<stdlib.h> 7 #include<algorithm> 8 #include<iostream> 9 #include<queue> 10 #include<map> 11 #include<math.h> 12 using namespace std; 13 typedef long long ll; 14 //typedef __int64 int64; 15 const int maxn = 1005; 16 const int inf = 0x7fffffff; 17 const double pi=acos(-1.0); 18 const double eps = 1e-8; 19 int dp[ maxn ][ maxn ]; 20 char s1[ maxn ],s2[ maxn ]; 21 bool ss[ 30 ][ 30 ]; 22 //map<char,char>mp; 23 void init(){ 24 memset( dp,0,sizeof( dp ) ); 25 //for( int i=0;i<26;i++ ){ 26 //mp[ 'a'+i ] = '@'; 27 //} 28 memset( ss,false,sizeof( ss ) ); 29 } 30 bool same( int x,int y ){ 31 if( s1[x]==s2[y]||ss[s2[y]-'a'][s1[x]-'a']==true ) return true; 32 else return false; 33 } 34 int main(){ 35 int T; 36 while( scanf("%d",&T)!=EOF ){ 37 int Case = 1; 38 while( T-- ){ 39 scanf("%s",s1); 40 scanf("%s",s2); 41 init(); 42 int q; 43 scanf("%d",&q); 44 char a[12],b[12]; 45 while( q-- ){ 46 scanf("%s",a); 47 scanf("%s",b); 48 ss[a[0]-'a'][b[0]-'a']=true; 49 //mp[ a[0] ] = b[0]; 50 } 51 int len1 = strlen( s1 ); 52 int len2 = strlen( s2 ); 53 for( int i=0;i<=len1;i++ ) 54 dp[ i ][ 0 ] = 0; 55 for( int i=0;i<=len2;i++ ) 56 dp[ 0 ][ i ] = 0; 57 for( int i=1;i<=len1;i++ ){ 58 for( int j=1;j<=len2;j++ ){ 59 if( same( i-1,j-1 )==true ) 60 dp[ i ][ j ] = dp[ i-1 ][ j-1 ]+1; 61 else 62 dp[ i ][ j ] = max( dp[i-1][j],dp[i][j-1] ); 63 //printf("dp[%d][%d]=%d\n",i,j,dp[i][j]); 64 } 65 } 66 if( dp[len1][len2]!=len1 ) printf("Case #%d: unhappy\n",Case++); 67 else printf("Case #%d: happy\n",Case++); 68 } 69 } 70 return 0; 71 }
keep moving...