結果

問題 No.422 文字列変更 (Hard)
ユーザー cielciel
提出日時 2015-10-24 04:02:35
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 198 ms / 3,000 ms
コード長 1,792 bytes
コンパイル時間 454 ms
コンパイル使用メモリ 64,120 KB
実行使用メモリ 125,568 KB
最終ジャッジ日時 2024-04-28 14:04:22
合計ジャッジ時間 3,532 ms
ジャッジサーバーID
(参考情報)
judge4 / judge1
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 23 ms
36,608 KB
testcase_01 AC 153 ms
98,048 KB
testcase_02 AC 165 ms
104,320 KB
testcase_03 AC 142 ms
93,056 KB
testcase_04 AC 152 ms
98,048 KB
testcase_05 AC 167 ms
107,392 KB
testcase_06 AC 196 ms
125,568 KB
testcase_07 AC 23 ms
36,608 KB
testcase_08 AC 26 ms
41,728 KB
testcase_09 AC 191 ms
118,016 KB
testcase_10 AC 198 ms
123,136 KB
testcase_11 AC 150 ms
99,072 KB
testcase_12 AC 143 ms
92,160 KB
testcase_13 AC 140 ms
94,720 KB
testcase_14 AC 146 ms
96,128 KB
testcase_15 AC 146 ms
96,640 KB
testcase_16 AC 150 ms
99,072 KB
権限があれば一括ダウンロードができます

ソースコード

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 9 + 2*(m - b - 1);
	}
	if(b == m) {
		return 9 + 2*(n - a - 1);
	}
	if(dp[a][b][s] != -1)return dp[a][b][s];

	int res = 1 << 25;
	pos np;
	
	// 変更してみる
	update(res, np, a + 1, b + 1, normal, (S[a] == T[b]) ? 0 : 5);
	// 挿入してみる
	update(res, np, a, b + 1, insert, (s == insert) ? 2 : 9);
	// 削除してみる
	update(res, np, a + 1, b, del, (s == del) ? 2 : 9);

	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