首页 > 代码库 > UVa 1509 - Leet

UVa 1509 - Leet

题目:给你一个小写的串,其中每个字母可以替换成k个字符(1~3),同一字母只能对应一个替换;

            不同字母替换可以相同,给你一个转化后的串问是不是一个合法替换。

分析:搜索。按顺序搜索即可,每次枚举长度从1~k的所有替换。

            如果当前字母未被替换,则可以任意替换,如果已经替换,只能选取相同替换向下搜索。

说明:题目只能看pdf版的o(╯□╰)o。

#include <iostream> 
#include <cstdlib>
#include <cstring>
#include <cstdio>

using namespace std;

char maps[26][4],temp[4];
char word[20],leet[100];

int dfs(int k, int p1, int p2 ,int l1, int l2)
{
	if (p1 == l1 && p2 == l2) return 1;
	if (p1 == l1 || p2 == l2) return 0;
	for (int i = 0 ; i < k ; ++ i) 
		if (p2+i < l2) {
			/*组成匹配方案*/
			temp[0] = temp[1] = temp[2] = temp[3] = 0;
			for (int j = 0 ; j <= i ; ++ j) temp[j] = leet[p2+j];
			/*原来无方案*/
			int flag = 0;
			if (!strcmp(maps[word[p1]-'a'],"")) {
				flag = 1;
				strcpy(maps[word[p1]-'a'],temp);
			} 
			if (flag || !strcmp(maps[word[p1]-'a'],temp))
				if(dfs(k,p1+1,p2+i+1,l1,l2)) return 1;
			/*回溯*/ 
			if (flag) strcpy(maps[word[p1]-'a'],"");
		}
	return 0;
}

int main()
{
	int n,k;
	while (cin >> n)
	while (n --) {
		cin >> k >> word >> leet;
		if (strlen(leet) > 3*strlen(word)) {
			cout << 0 << endl;
			continue;
		}
		
		for (int i = 0 ; i < 26 ; ++ i)
			strcpy(maps[i],"");
		cout << dfs(k,0,0,strlen(word),strlen(leet)) << endl;
	}
	return 0;
}

UVa 1509 - Leet