9度OJ 1042 Coincidence--ダイナミック企画(最長共通サブシーケンス)
1494 ワード
タイトルの住所:http://ac.jobdu.com/problem.php?pid=1042
テーマの説明:
Find a longest common subsequence of two stings.
入力:
First and second line of each input case contain two streings of lowercase character a...z.The areのspaces before、inside or after the streings.Lengths of stregs do exceed 100.
出力:
For each case,output k–the length of a longest common subsequence in one line.
サンプル入力:
参考資料:http://www.cnblogs.com/liyukuneed/archive/2013/05/22/3090597.html
テーマの説明:
Find a longest common subsequence of two stings.
入力:
First and second line of each input case contain two streings of lowercase character a...z.The areのspaces before、inside or after the streings.Lengths of stregs do exceed 100.
出力:
For each case,output k–the length of a longest common subsequence in one line.
サンプル入力:
abcd
cxbydz
サンプル出力:2
#include <stdio.h>
#include <string.h>
#define MAX 101
int main(void){
char first[MAX], second[MAX];
int len1, len2;
int i, j;
int subseq[2][MAX];
while (scanf ("%s%s", first, second) != EOF){
len1 = strlen (first);
len2 = strlen (second);
for (i=0; i<=len2; ++i)
subseq[0][i] = 0;
subseq[1][0] = 0;
for (i=1; i<=len1; ++i){
for (j=1; j<=len2; ++j){
if (first[i-1] == second[j-1])
subseq[i%2][j] = subseq[(i-1)%2][j-1] + 1;
else{
subseq[i%2][j] = (subseq[(i-1)%2][j] > subseq[i%2][j-1]) ? subseq[(i-1)%2][j] : subseq[i%2][j-1];
}
}
}
printf ("%d
", subseq[len1%2][len2]);
}
return 0;
}
HDOJで似たようなテーマ:http://acm.hdu.edu.cn/showproblem.php?pid=1243 参考資料:http://www.cnblogs.com/liyukuneed/archive/2013/05/22/3090597.html