Krypton Factor UVA - 129 

回朔法

复杂度 不会算

代码参考刘汝佳的代码仓库

补充:回朔法类似于枚举,但快于枚举,因为在进行递归时会判断,导致了某些情况不需要进一步在枚举下去,这样就减少了时间

如果能用枚举解决的问题,适当考虑用回溯

#include<iostream>
#include<cmath>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#pragma warning(disable:4996)
using namespace std;
int S[100], k, L, cnt;
int dfs(int cur)
{
	if (cnt++ == k) 
	{
		for (int i = 0; i < cur; i++) {
			if (i % 64 == 0 && i > 0) printf("\n");
			else if (i % 4 == 0 && i > 0) printf(" ");
			printf("%c", 'A' + S[i]); // 输出方案
		}
		printf("\n%d\n", cur);
		return 0;
	}
	for (int i = 0; i < L; i++)
	{
		S[cur] = i; bool ok = true;
		for (int j = 1; 2 * j <= cur + 1; j++)
		{
			bool equal = true;
			for (int m = 0; m < j; m++) if (S[cur - m] != S[cur - m - j]) { equal = false; break; }
			if (equal) { ok = false; break; }
		}
		if (ok) if (!dfs(cur + 1)) return 0;
	}
	return 1;
}
int main()
{
	while (scanf("%d%d", &k, &L) == 2 && k > 0)
	{
		cnt = 0;
		dfs(0);
	}
}

猜你喜欢

转载自blog.csdn.net/qq_41776911/article/details/82386678
129
今日推荐