結果

問題 No.422 文字列変更 (Hard)
ユーザー krotonkroton
提出日時 2015-06-13 06:14:09
言語 C++11
(gcc 11.4.0)
結果
WA  
実行時間 -
コード長 2,224 bytes
コンパイル時間 581 ms
コンパイル使用メモリ 63,848 KB
実行使用メモリ 131,624 KB
最終ジャッジ日時 2024-04-28 14:04:04
合計ジャッジ時間 3,576 ms
ジャッジサーバーID
(参考情報)
judge2 / judge4
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 WA -
testcase_01 WA -
testcase_02 WA -
testcase_03 WA -
testcase_04 WA -
testcase_05 WA -
testcase_06 WA -
testcase_07 WA -
testcase_08 WA -
testcase_09 AC 188 ms
117,888 KB
testcase_10 WA -
testcase_11 WA -
testcase_12 WA -
testcase_13 WA -
testcase_14 WA -
testcase_15 WA -
testcase_16 WA -
権限があれば一括ダウンロードができます

ソースコード

diff #

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

int n, m;
string S, T;

enum state {
	normal,
	del,
	insert
};

typedef tuple<int, int, state> pos;

int dp[1300][1300][5];
pos nxt[1300][1300][5];

int solve(int, int, state);
void update(int& res, pos& p, int a, int b, state s, int add) {
	int cost = solve(a, b, s) + add;
	if(cost < res) {
		res = cost;
		p = make_tuple(a, b, s);
	}
}

int solve(int a, int b, state s) {
	if(a == n && b == m) {
		return 0;
	}
	if(a == n) {
		return 5 + (m - b - 1);
	}
	if(b == m) {
		return 5 + (n - a - 1);
	}
	if(dp[a][b][s] != -1)return dp[a][b][s];

	int res = 1 << 25;
	pos np;

	switch (s) {
	case normal:
		if(S[a] == T[b]) {
			// 一致してるのでそのまま進む
			update(res, np, a + 1, b + 1, normal, 0);
		}
		// 変更してみる
		update(res, np, a + 1, b + 1, normal, 5);
		// 挿入してみる
		update(res, np, a, b + 1, insert, 5);
		// 削除してみる
		update(res, np, a + 1, b, del, 5);
		break;

	case del:
		if(S[a] == T[b]) {
			// 一致してるのでここでノーマルに戻してみる
			update(res, np, a + 1, b + 1, normal, 0);
		}
		// まだ削除する
		update(res, np, a + 1, b, del, 1);
		break;

	case insert:
		if(S[a] == T[b]) {
			// 一致しているのでノーマルに戻してみる
			update(res, np, a + 1, b + 1, normal, 0);
		}
		// まだ挿入する
		update(res, np, a, b + 1, insert, 1);
		break;
	}

	nxt[a][b][s] = np;
	return dp[a][b][s] = res;
}

string accS, accT;

void dfs(int a, int b, state s) {
	if(a == n && b == m) {
		return;
	}
	if(a == n) {
		accS += string(m - b, '_');
		accT += T.substr(b);
		return;
	}
	if(b == m) {
		accS += S.substr(a);
		accT += string(n - a, '_');
		return;
	}

	pos np = nxt[a][b][s];
	int na = get<0>(np), nb = get<1>(np);
	state ns = get<2>(np);

	switch (ns) {
	case normal:
		accS += S[a];
		accT += T[b];
		break;
	case del:
		accS += S[a];
		accT += '_';
		break;
	case insert:
		accS += '_';
		accT += T[b];
		break;
	}

	dfs(na, nb, ns);
}

int main() {
	memset(dp, -1, sizeof(dp));

	cin >> n >> m;
	cin >> S >> T;

	cout << solve(0, 0, normal) << endl;

	dfs(0, 0, normal);
	cout << accS << endl;
	cout << accT << endl;

	return 0;
}
0