HDU 1503

就是最长公共子序列的加强版,回溯记录一下最长的那个子序列,然后输出即可

不过我的代码一直WA,也没有找到什么错误,桑心

WA代码:

#include <cstdio>
#include <iostream>
#include <cstring>

using namespace std;

#define LEN 110
#define MAX(A,B) (A>B?A:B)

int dp[LEN][LEN];
char str1[LEN], str2[LEN];
int mark1[LEN], mark2[LEN];

int main() {
	while(scanf("%s%s", str1+1, str2+1) != EOF) {
		int i, j;
		int len1, len2;
		int index, tmp, ilen1, ilen2;
		str1[0] = str2[0] = '0';
		len1 = strlen(str1)-1;
		len2 = strlen(str2)-1;
		memset(dp, 0, sizeof(dp));
		memset(mark1, 0, sizeof(mark1));
		memset(mark2, 0, sizeof(mark2));
		for(i = 1; i <= len1; i++) {
			for(j = 1; j <= len2; j++) {
				if(str1[i] == str2[j]) {
					dp[i][j] = dp[i-1][j-1]+1;
				}
				else {
					dp[i][j] = MAX(dp[i-1][j], dp[i][j-1]);
				}
			}
		}
		tmp = dp[len1][len2];
		ilen1 = len1;
		ilen2 = len2;
		for(i = ilen1; i > 0; i--) {
			for(j = ilen2; j > 0; j--) {
				if(tmp == 1+dp[i][j-1] && tmp == 1+dp[i-1][j]) {
					ilen1 = i-1;
					ilen2 = j-1;
					mark1[i] = 1;
					mark2[j] = 1;
					tmp--;
					break;
				}
			}
		}

		index = 1;
		for(i = 1; i <= len1; i++) {
			if(0 == mark1[i]) {
				printf("%c", str1[i]);
				continue;
			}
			for(j = index; j <= len2; j++) {
				if(0 == mark2[j]) {
					printf("%c", str2[j]);
				}
				else {
					index = j+1;
					break;
				}
			}
			if(j != len2+1) {
				printf("%c", str1[i]);
			}
		}
		for(j = j+1; j <= len2; j++) {
			printf("%c", str2[j]);
		}
		printf("\n");
	}
	return 0;
}


copy一个看着挺好的代码:

#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
char str1[105],str2[105];
int dp[105][105],flag[105][105];
void printf_route(int x,int y)
{
    if(x==0&&y==0)
        return ;
    if(flag[x][y]==y+1)
    {
        printf_route(x-1,y-1);
        putchar(str1[x]);
    }
    else if(flag[x][y]==y)
    {
        printf_route(x-1,y);
        putchar(str1[x]);
    }
    else
    {
        printf_route(x,y-1);                         
        putchar(str2[y]);
    }
    return ;
}
int main()
{
    int i,j;
    while(scanf("%s%s",str1+1,str2+1)!=EOF)
    {
        int len1=strlen(str1+1);
        int len2=strlen(str2+1);
        for(i=0;i<=len1;i++)
            dp[i][0]=0;
        for(i=0;i<=len2;i++)
            dp[0][i]=0;
        for(i=1;i<=len1;i++)
            for(j=1;j<=len2;j++)
            {
                if(str1[i]==str2[j])
                {
                    dp[i][j]=dp[i-1][j-1]+1;
                    flag[i][j]=j+1;
                }
                else if(dp[i-1][j]<dp[i][j-1])
                {
                    dp[i][j]=dp[i][j-1];
                    flag[i][j]=j-1;
                }
                else
                {
                    dp[i][j]=dp[i-1][j];
                    flag[i][j]=j;
                }
            }
        printf_route(len1,len2);
        puts("");
    }
    return 0;
}


 

你可能感兴趣的:(HDU 1503)