最長公共子序列 nyoj

最長公共子序列

時間限制:3000 ms  |  內存限制:65535 KB
難度:3
描述
咱們就不拐彎抹角了,如題,需要你做的就是寫一個程序,得出最長公共子序列。
tip:最長公共子序列也稱作最長公共子串(不要求連續),英文縮寫爲LCS(Longest Common Subsequence)。其定義是,一個序列 S ,如果分別是兩個或多個已知序列的子序列,且是所有符合此條件序列中最長的,則 S 稱爲已知序列的最長公共子序列。
輸入
第一行給出一個整數N(0<N<100)表示待測數據組數
接下來每組數據兩行,分別爲待測的兩組字符串。每個字符串長度不大於1000.
輸出
每組測試數據輸出一個整數,表示最長公共子序列長度。每組結果佔一行。
樣例輸入
2
asdf
adfsd
123abc
abc123abc
樣例輸出
3
6
 
#include<stdio.h>
#include <string.h>
#define Max_len 1001

int record[Max_len][Max_len];
int len_lcs(char x[], char y[]);

int main (){
	
	int N, record;
	char x[Max_len];
	char y[Max_len];

	scanf("%d", &N);
	while(N--){
		scanf("%s %s", x, y);
		record = len_lcs(x, y);
		printf("%d\n", record);
	}
}

int len_lcs(char x[], char y[]){
	
	int n = strlen(x);
	int m = strlen(y);
	int i, j;	

	for(i = 0; i < n; i++){
		record[i][0] = 0;
	}

	for(i = 0; i < m; i++) {
		record[0][i] = 0;
	}

	for(i = 1; i <= n; i++){
		for(j = 1; j <= m; j++){
			if(x[i - 1] == y[j - 1]){
				record[i][j] = record[i - 1][j - 1] + 1;
			}
			else if(record[i - 1][j] > record[i][j - 1]){
				record[i][j] = record[i - 1][j];
			}
			else{
				record[i][j] = record[i][j - 1];
			}
		}
	}

	return record[n][m];
}        



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章