ACM - Common Subsequence (HDU 1159)

Common Subsequence

#include <iostream>
#include <string>
#include <algorithm>

#define MAX 1010

using namespace std;

int dp[MAX][MAX];
string strA, strB;

void init() {
	int len = max(strA.length(), strB.length());
	for (int i = 0; i <= len; i++) {
		for (int j = 0; j <= len; j++) {
			dp[i][j] = 0;
		}
	}
}

void solve() {
	for (int i = 0; i <= strA.length(); i++) {
		for (int j = 0; j <= strB.length(); j++) {
			if (i == 0 || j == 0) {
				dp[i][j] = 0;
			}
			else if (strA[i - 1] == strB[j - 1]) {
				dp[i][j] = dp[i - 1][j - 1] + 1;
			}
			else {
				dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
			}
		}
	}
	cout << dp[strA.length()][strB.length()] << endl;
}

int main() {
	while (cin >> strA >> strB) {
		init();
		solve();
	}
}

猜你喜欢

转载自blog.csdn.net/AyaMisaki/article/details/85059321