您的位置:首页 > 产品设计 > UI/UE

hdu 1503 Advanced fruits

2015-09-07 23:16 375 查看
解题思路:这道题就是给你两个单词,然后你要把两个单词拼接成一个新单词,使得新单词的子序列中包含两个单词,

并且要使这个新单词最短。所以这道题就是求最长公共子序列,并且要记录下子序列的字母,以及他们在主串和副串

中的原始位置,之后进行拼接输出。

// Created by Chenhongwei in 2015.
// Copyright (c) 2015 Chenhongwei. All rights reserved.

#include"iostream"
#include"cstdio"
#include"cstdlib"
#include"cstring"
#include"climits"
#include"queue"
#include"cmath"
#include"map"
#include"set"
#include"stack"
#include"vector"
#include"sstream"
#include"algorithm"
using namespace std;
typedef long long ll;
char s[110],t[110];
int dp[110][110];
int r[110][110],h[110];
int main()
{
//ios::sync_with_stdio(false);
// freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
while(scanf("%s%s",s+1,t+1)!=EOF)
{
memset(dp,0,sizeof dp);
memset(h,-1,sizeof h);
memset(r,-1,sizeof r);
int ls=strlen(s+1);
int lt=strlen(t+1);
for(int i=1;i<=ls;i++)
for(int j=1;j<=lt;j++)
if(s[i]==t[j])
{
dp[i][j]=dp[i-1][j-1]+1;
r[i][j]=0;
}
else if(dp[i-1][j]>dp[i][j-1])
{
dp[i][j]=dp[i-1][j];
r[i][j]=1;
}
else
{
dp[i][j]=dp[i][j-1];
r[i][j]=2;
}
// for(int i=0;i<=ls;i++)
// {
// for(int j=0;j<=lt;j++)
// cout<<r[i][j]<<" ";
// cout<<endl;
// }
int x=ls,y=lt;
while(r[x][y]!=-1)
{
if(r[x][y]==0)
{
h[x]=y;
x--,y--;
}
else if(r[x][y]==1)
x--;
else if(r[x][y]==2)
y--;
}
int start=1;
for(int i=1;i<=ls;i++)
{
if(h[i]==-1)
{
cout<<s[i];
continue;
}
for(int j=start;j<=h[i];j++)
cout<<t[j];
start=h[i]+1;
}
for(int j=start;j<=lt;j++)
cout<<t[j];
cout<<endl;
}
return 0;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: