UVA 10981 - String Morphing(记忆化搜索)

题目链接:10981 - String Morphing

题意:给定开始的字符串,要求根据表格变化成一个字符串,问变化的顺序(注意,不一定要最少步数)
思路:记忆化搜索,用map来存字符串的状态,一开始按最少步数去做TLE,其实只要找到一个符合的就可以了
代码:
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <string>
#include <map>
using namespace std;
#define min(a,b) ((a)<(b)?(a):(b))
#define INF 0x3f3f3f3f
const int N = 105;
int t;
string start, end;
char g[105][105];
map<string, int> dp;
map<string, string> z;

int dfs(string start) {
	if (dp.count(start)) return dp[start];
	dp[start] = 0;
	if (start == end) return dp[start] = 1;
	for (int i = 0; i < start.size() - 1; i++) {
		string tmp = "";
		tmp += g[start[i]][start[i + 1]];
		string s = start;
		if (dfs(s.replace(i, 2, tmp))) {
			z[start] = s;
			return dp[start] = 1;
		}
	}
	return dp[start];
}

void print(string start) {
	cout << start << endl;
	if (start == end) return;
	print(z[start]);
}

int main() {
	g['a']['a'] = g['a']['b'] = g['b']['b'] = 'b';
	g['a']['c'] = g['b']['c'] = g['c']['a'] = 'a';
	g['b']['a'] = g['c']['b'] = g['c']['c'] = 'c';
	scanf("%d", &t);
	while (t--) {
		z.clear();
		dp.clear();
		cin >> start >> end;
		if (start.size() < end.size()) {
			printf("None exist!\n");
			continue;
		}
		if (dfs(start)) print(start);
		else printf("None exist!\n");
		if (t) printf("\n");
	}
	return 0;
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值