HDU 1503 Advanced Fruits

题意:将两个单词合并,重复的部分只输出一次。

分析:最长递增子序列的变形,只是输出的地方发生了变化

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int MN=200;
int len1,len2;
int b[MN][MN];
char s1[MN],s2[MN];
int c[MN][MN];
  
void LCSLenth()
{
    int i,j;
    memset(c,0,sizeof(c));
    for(i=1; i<=len1; i++)
    {
        for(j=1; j<=len2; j++)
        {
            if(s1[i-1]==s2[j-1])
            {
                c[i][j]=c[i-1][j-1]+1;
                b[i][j]=0;
            }
            else if(c[i][j-1]<=c[i-1][j])
            {
                c[i][j]=c[i-1][j];
                b[i][j]=1;//从上边
            }
            else
            {
                c[i][j]=c[i][j-1];
                b[i][j]=2;//从左边
            }
        }
    }
}
  
void Print(int i,int j)
{
    if(i==0 && j==0) return ;
    else if(i==0 && j!=0)
    {
        Print(i,j-1);
        printf("%c",s2[j-1]);
    }
    else if(i!=0 && j==0)
    {
        Print(i-1,j);
        printf("%c",s1[i-1]);
    }
    else if(b[i][j]==0)
    {
        Print(i-1,j-1);
        printf("%c",s1[i-1]);
    }
    else if(b[i][j]==1)
    {
        Print(i-1,j);
        printf("%c",s1[i-1]);
    }
    else
    {
        Print(i,j-1);
        printf("%c",s2[j-1]);//若从右边过来的,则打印s2
        //因为对于i是没发生变化的,也就是说s1序列位置没发生变化
    }
}
  
  
int main()
{
    int i,j;
    while(scanf("%s%s",&s1,&s2)!=EOF)
    {
        len1=strlen(s1);
        len2=strlen(s2);
        LCSLenth();
        Print(len1,len2);
        printf("\n");
    }
    return 0;
}
原文地址:https://www.cnblogs.com/zsboy/p/2963194.html