要点:
1.比较基础的lcs题,关键在于输入时用字符串输入,输出时用递归
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int len1, len2;
char a[500][35], b[500][35];
int num[500][500], flag[500][500];void lcs()
{int i, j;for (i = 1; i <= len1; i++){for (j = 1; j <= len2; j++){if (strcmp(a[i-1], b[j-1]) == 0){num[i][j] = num[i - 1][j - 1] + 1;flag[i][j] = 1;}else if (num[i - 1][j]>num[i][j - 1]){num[i][j] = num[i - 1][j];flag[i][j] = 2; //标记向下}else{num[i][j] = num[i][j - 1];flag[i][j] = 3; //标记向右}}}
}void getlcs(int i,int j) //这里要用递归,用数组赋值会出现格式不匹配
{if (i == 0 || j == 0) //i或j触底return;if (flag[i][j] == 1){getlcs(i - 1, j - 1);printf("%s ", a[i - 1]); //注意这里是输出i-1}else if (flag[i][j] == 2)getlcs(i - 1, j);elsegetlcs(i, j - 1);
}int main()
{int i, j;while (scanf("%s", a[0]) != EOF) //先输入第一个{ //用%s输入一个个字符串,比一个个字符输入减少时间for (len1 = 1;; len1++){scanf("%s", a[len1]);if (strcmp(a[len1], "#") == 0)break;}for (len2 = 0;; len2++){scanf("%s", b[len2]);if (strcmp(b[len2], "#") == 0)break;}lcs();getlcs(len1,len2);printf("\n");}return 0;
}