您的位置:首页 > 其它

HDU 1503 带回朔路径的最长公共子串

2016-03-15 13:58 302 查看
http://acm.hdu.edu.cn/showproblem.php?pid=1503

这道题又WA了好几次

在裸最长公共子串基础上加了回溯功能,就是给三种状态各做一个

不同的标记。dp
[m]开始回找,找到这条最长串的组成。

WA点有几个都被我遇到了

一个是最长公共串为0时,两个串直接输出

一个是最长公共串为1时,后续串的处理

这里要记得是dp回溯的方式

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<string>
#include<stack>
#include<cstring>
using namespace std;
struct donser
{
int x,y;
};
int main()
{
string s,t;
while(cin>>s>>t)
{
int i,j,m=0,n=0,a1,b1,a2,b2;
stack<donser> sta;
struct donser dong;
struct donser dongs;
int dp[200][200],lable[200][200];
n=s.length();
m=t.length();
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
if(s[i]==t[j])
{
dp[i+1][j+1]=dp[i][j]+1;
lable[i+1][j+1]=1;
}
else
{
if(dp[i][j+1]>dp[i+1][j])
{
dp[i+1][j+1]=dp[i][j+1];
lable[i+1][j+1]=2;
}
else
{
dp[i+1][j+1]=dp[i+1][j];
lable[i+1][j+1]=3;
}
}
}
}
i=n;j=m;a1=a2=n;b1=b2=m;
if(dp
[m]==0){cout<<s<<t<<endl;}
else{
while(lable[i][j]!=0)
{
if(lable[i][j]==1)
{
i--;j--;
dong.x=i;
dong.y=j;
sta.push(dong);
}
else if(lable[i][j]==2)
{
i--;
}
else if(lable[i][j]==3)
{
j--;
}
}
if(sta.empty()!=1)
{
dong=sta.top();
sta.pop();
a1=dong.x;
b1=dong.y;
for(i=0;i<a1;i++)
{
cout<<s[i];
}
for(i=0;i<b1;i++)
{
cout<<t[i];
}
}
if(sta.empty()==1)
{
for(i=a1;i<n;i++)
{
cout<<s[i];
}
for(i=b1+1;i<m;i++)
{
cout<<t[i];
}
}
while(sta.empty()!=1)
{
a1=dong.x;
b1=dong.y;
dongs=sta.top();
sta.pop();
a2=dongs.x;
b2=dongs.y;
for(i=a1;i<a2;i++)
{
cout<<s[i];
}
for(j=b1+1;j<b2;j++)
{
cout<<t[j];
}
dong=dongs;
}
for(i=a2;i<n;i++)
{
cout<<s[i];
}
for(i=b2+1;i<m;i++)
{
cout<<t[i];
}
cout<<endl;}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: