题意:给两个字符串,然后将这两个字符串合到一起形成一个新字符串,两个字符串在新串中顺序不变,且保证新字符串长度最短,问最短长度是多少,有多少种新字符串。

题解:f[i][j]和len[i][j]分别表示str1中前i个字符和str2中前j个字符可以组成的新字符串的种类数量和长度,迭代做法,如果str1[i] == str2[j],状态转移方程f[i][j] = f[i - 1][j - 1] len[i][j] = len[i - 1][j - 1] + 1,否则len[i][j] = min(len[i - 1][j], len[i][j - 1]), f[i][j]根据len[i - 1][j] 和 len[i][j - 1]确定。

#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
const int N = 35;
char str1[N], str2[N];
int f[N][N], len[N][N], len1, len2;

int main() {
	int t, cas = 1;
	scanf("%d", &t);
	getchar();
	while (t--) {
		gets(str1);
		gets(str2);
		len1 = strlen(str1);
		len2 = strlen(str2);
		for (int i = 1; i <= len1; i++) {
			len[i][0] = i;
			f[i][0] = 1;
		}
		for (int i = 1; i <= len2; i++) {
			len[0][i] = i;
			f[0][i] = 1;
		}
		f[0][0] = 1;
		for (int i = 1; i <= len1; i++) {
			for (int j = 1; j <= len2; j++) {
				if (str1[i - 1] == str2[j - 1]) {
					len[i][j] = len[i - 1][j - 1] + 1;
					f[i][j] = f[i - 1][j - 1];
				}
				else {
					len[i][j] = min(len[i - 1][j], len[i][j - 1]) + 1;
					if (len[i - 1][j] == len[i][j - 1])
						f[i][j] = f[i - 1][j] + f[i][j - 1];
					else if (len[i - 1][j] > len[i][j - 1])
						f[i][j] = f[i][j - 1];
					else
						f[i][j] = f[i - 1][j];
				}
			}
		}
		printf("Case #%d: %d %d\n", cas++, len[len1][len2], f[len1][len2]);
	}
	return 0;
}