最長公共子序列

最長公共子序列

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

hzyqazasdf


#include<iostream>
#include<cstring>
using namespace std;

int n,count;
int arr[1008][1008];
string x,y;

int main()
{
	int i,j;
	
	cin>>n;
	while(n--)
	{   
	    cin>>x>>y;
	    count=0;
		int x_lenth=x.length();
		int y_lenth=y.length();
		
		int arr[1008][1008]={{0,0}};
		
		int i=0;
		int j=0;
		
		for(i=1;i<=x_lenth;i++)
		{
			for(j=1;j<=y_lenth;j++)
			{
				if(x[i-1]==y[j-1])
				{
					arr[i][j]=arr[i-1][j-1]+1;
				}
				else
				{
					if(arr[i][j-1]>=arr[i-1][j])
					arr[i][j]=arr[i][j-1];
					else
					arr[i][j]=arr[i-1][j];
				}
			}
		}
		for(i=x_lenth,j=y_lenth;i>=1&&j>=1;)
		{
			if(x[i-1]==y[j-1])
			{
				count++;
				i--;
				j--;
			}
			else
			{
				if(arr[i][j-1]>arr[i-1][j])
				{
					j--;
				}
				else
				{
					i--;
				}
			}
		}
		cout<<count<<endl;
	}
	return 0;
}


發佈了60 篇原創文章 · 獲贊 20 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章