其实说白了就是最长公共子序列,就是第二个序列是可以相应的进行变化的。其实用一个数组存一下这个到底是哪个字符可以相应的变成对应的字符就可以了。水题不解释贴代码。
#include<iostream>
#include<string>
using namespace std;
int dp[1005][1005];
bool has[128][128];
int maxi(int x,int y)
{
if(x>y)
return x;
else return y;
}
int main()
{
int i,j,t,m,count=0,len1,len2;
char a,b;
string str1,str2;
cin>>t;
while(t--)
{
count=count+1;
cin>>str1>>str2;
len1=str1.size();
len2=str2.size();
memset(dp,0,sizeof(dp));
memset(has,-1,sizeof(has));
cin>>m;
for(j=1;j<=m;j++)
{
cin>>a>>b;
has[a][b]=1;
}
for(i=1;i<=len1;i++)
for(j=1;j<=len2;j++)
{
if(str1[i-1]==str2[j-1]||has[str2[j-1]][str1[i-1]]==1)
dp[i][j]=dp[i-1][j-1]+1;
else dp[i][j]=maxi(dp[i-1][j],dp[i][j-1]);
}
cout<<"Case #"<<count<<": ";
if(dp[len1][len2]==len1)
cout<<"happy"<<endl;
else cout<<"unhappy"<<endl;
}
return 0;
}