hdu 1503 Advanced Fruits

http://acm.hdu.edu.cn/showproblem.php?pid=1503

最长公共子序列 用个p[i][j]记录dp[i][j]是从哪个位置传递过来的

然后dfs输出,基本都是看的别人题解,然后自己写的,就不多说了

代码:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <map>
#include <set>
#include <queue>
using namespace std;
char word1[105];
char word2[105];
int dp[105][105];
int p[105][105];
int dfsprint(int n,int m)
{
    //printf("%d %d\n",n,m);
    if(n==0&&m==0)
    return 1;
    else if(n==0&&m!=0)
    {
        dfsprint(n,m-1);
        printf("%c",word2[m]);
    }
    else if(n!=0&&m==0)
    {
        dfsprint(n-1,m);
        printf("%c",word1[n]);
    }
    else if(p[n][m]==1)
    {
        dfsprint(n-1,m-1);
        printf("%c",word1[n]);
    }
    else if(p[n][m]==2)
    {
        dfsprint(n,m-1);
        printf("%c",word2[m]);
    }
    else
    {
        dfsprint(n-1,m);
        printf("%c",word1[n]);
    }
}
int main()
{
    while(scanf("%s%s",word1+1,word2+1)==2)
    {
        int lena=strlen(word1+1);
        int lenb=strlen(word2+1);
        memset(dp,0,sizeof(dp));
        for(int i=1;i<=lena;i++)
        for(int j=1;j<=lenb;j++)
        {
            if(word1[i]==word2[j])
            {
                dp[i][j]=dp[i-1][j-1]+1;
                p[i][j]=1;
            }
            else if(dp[i][j-1]>=dp[i-1][j])
            {
                dp[i][j]=dp[i][j-1];
                p[i][j]=2;
            }
            else
            {
                dp[i][j]=dp[i-1][j];
                p[i][j]=3;
            }
        }
        dfsprint(lena,lenb);
        printf("\n");
    }
}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值