Poj-2250-Compromise

题意是找两篇文章中的最长子单词序列

能得出个数,但不知如何输出,找不到路径

看了别人的dfs,有所领悟:

若输入s1:ab,bd,fk,ce,ak,bt,cv

s2: ab,fk,ce,tt,ak,bt,深搜路径数字涂红
dp棋盘如下:
           ab   fk   ce   tt   ak   bt  <-s2

              0       0        0        0        0       0        0

 ab         0       1        1        1    1    1    1        输出 ab

 bd   0   1    1    1     1    1    1

 fk    0   1    2    2     2    2    2        输出 fk

 ce   0    1    2    3    3    3    3         输出 ce

 ak   0    1    2    3    3    4    4         输出 ak

 bt   0    1     2    3    3    4    5         输出 bt 

 cv   0    1    2     3    3    4    5

 ^
 s1

代码如下:

#include<stdio.h>
#include<string.h>
int dp[102][102];
char s1[102][33],s2[102][33];
int max(int x,int y)
{
    return x>y?x:y;
}
int dfs(int a,int b)
{
    if(dp[a][b]==0)
        return 0;
    if(dp[a][b]==dp[a-1][b-1]+1&&strcmp(s1[a],s2[b])==0)
    {
        dfs(a-1,b-1);
        if(dp[a][b]==1)
            printf("%s",s1[a]);
        else
            printf(" %s",s1[a]);
    }
    else
        if(dp[a][b]==dp[a-1][b])
            dfs(a-1,b);
        else
            dfs(a,b-1);
    return 0;
}
int main()
{
    int i,j;
    int L1,L2;
    while(scanf("%s",&s1[1])!=EOF)     //读到文件结束标志停止,下标为几就是第几个单词,便于输出
    {
        L1=1;L2=0;                    //L1为第一篇文章单词个数,L2为第二篇
        while(scanf("%s",&s1[++L1])==1)
            if(strcmp(s1[L1],"#")==0)   //读到 # 本篇文章结束
            {
                L1--;
                break;
            }
        while(scanf("%s",&s2[++L2])==1)
            if(strcmp(s2[L2],"#")==0)
            {
                L2--;
                break;
            }
        memset(dp,0,sizeof(dp));
        for(i=1; i<=L1; i++)           //初始化dp棋盘
            for(j=1; j<=L2; j++)
                if(strcmp(s1[i],s2[j])==0)
                    dp[i][j]=dp[i-1][j-1]+1;
                else
                    dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
        dfs(L1,L2);                   //从右下角开始搜
        printf("\n");
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/Houheshuai/p/3688389.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值