思路:dp(i, j)表示第一个串前i个字符和第二个串前j个字符需要的最短字符串长度,cnt(i, j)表示第一个串前i个字符和第二个串前j个字符需要的最短字符串的个数。

转移方程:

if(s1[i] == s2[j]) dp[i][j] = dp[i-1][j-1] + 1;
else dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1]);
if(s1[i] == s2[j]) cnt[i][j] = cnt[i-1][j-1]; //字符成功匹配
else {
	if(dp[i-1][j] == dp[i][j-1])
	        cnt[i][j] = cnt[i-1][j] + cnt[i][j-1];
	else if(dp[i-1][j] < dp[i][j-1])
		cnt[i][j] = cnt[i-1][j];
	else
		cnt[i][j] = cnt[i][j-1];
}

AC代码

#include <cstdio>
#include <cmath>
#include <cctype>
#include <algorithm>
#include <cstring>
#include <utility>
#include <string>
#include <iostream>
#include <map>
#include <set>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
#pragma comment(linker, "/STACK:1024000000,1024000000")
#define eps 1e-10
#define inf 0x3f3f3f3f
#define PI pair<int, int>
typedef long long LL;
const int maxn = 30 + 5;
char s1[maxn], s2[maxn];
int dp[maxn][maxn], cnt[maxn][maxn];
int main() {
	int T, kase = 1;
	scanf("%d", &T);
	getchar();
	while(T--) {
		fgets(s1+1, sizeof(s1), stdin);
		fgets(s2+1, sizeof(s2), stdin);
		//scanf("%s%s", s1+1, s2+1);
		int n = strlen(s1+1) - 1, m = strlen(s2+1) - 1;
		for(int i = 0; i < maxn; ++i) {
			dp[0][i] = dp[i][0] = i;
			cnt[0][i] = cnt[i][0] = 1;
		}
		for(int i = 1; i <= n; ++i)
			for(int j = 1; j <= m; ++j) {
				if(s1[i] == s2[j]) dp[i][j] = dp[i-1][j-1] + 1;
				else dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1]);
			}
		for(int i = 1; i <= n; ++i)
			for(int j = 1; j <= m; ++j) {
				if(s1[i] == s2[j]) cnt[i][j] = cnt[i-1][j-1];
				else {
					if(dp[i-1][j] == dp[i][j-1])
						cnt[i][j] = cnt[i-1][j] + cnt[i][j-1];
					else if(dp[i-1][j] < dp[i][j-1])
						cnt[i][j] = cnt[i-1][j];
					else
						cnt[i][j] = cnt[i][j-1];
				}
		}
		printf("Case #%d: %d %d\n", kase++, dp[n][m], cnt[n][m]);
	}
	return 0;
}

如有不当之处欢迎指出!

最新文章

  1. maven仓库信息分析站点推荐
  2. 备忘DES带向量的加密和解密与DES简单加密与解密
  3. CSS 自定义字体
  4. 爱上MVC~AuthorizeAttribute验证不通过如何停止当前上下文
  5. bug: 在使用HMSegmentedControl时,设置selectionIndicatorEdgeInsets对左右边界没有用
  6. ubuntu 16.04 tmux
  7. ORACLE将表中的数据恢复到某一个时间点
  8. Java Fluent Restful API自动化测试框架
  9. Linux下实现普通用户免密码登录【超详细】
  10. android6.0以上权限动态申请,有视频链接可以看效果。
  11. android 圆角背景
  12. JAVA核心技术I---JAVA基础知识(内部类)
  13. (2):Mysql 查看、创建、更改 数据库和表
  14. Spring注解开发之Spring常用注解
  15. [Web 前端] 如何构建React+Mobx+Superagent的完整框架
  16. qbxt联赛集训d1t3
  17. 点云库PCL学习
  18. .net core 2.2 部署CentOS7(2)给虚拟机安装CentOS7
  19. Linux进程间通信—消息队列
  20. DFS实现全排列

热门文章

  1. scrapy_移除内容中html标签
  2. linux指令--ls
  3. 如何用docker部署redis cluster
  4. java时间格式转化(毫秒 to 00:00)
  5. keytool 错误:java.to.FileNotFoundException:
  6. &lt;select&gt;设置multiple=&quot;multiple&quot;属性后 下拉框全部展开了 不再是折叠的怎么回事
  7. awk脚本使用的几种方法
  8. linux服务器配置pyspark解决py4j报错等问题
  9. C#中的out参数/ref参数/params可变参数
  10. bootstrap select2 使用简单介绍