您的位置:首页 > 其它

UVa129 - Krypton Factor 不错的DFS入门题

2015-01-29 23:59 387 查看
题意 一个字符串被称为容易串,指其中有相邻的两个相同的子串,反之为困难串。问你由前L个字符组成的字典序第k小的困难串。保证答案串长不超过80。

思路 难点在于如何判断当前串是否为困难串,整串比较O(n^3),但如果用dfs,每次只需要判断新加入的字母会不会使字符串为困难串即可,通过枚举不同长度的后缀即可,复杂度O(n^2)。是容易串就做可行性剪枝。

感觉这题非常适合dfs,整个就是为其设计的感觉,是入门dfs的好题~

#include <cstring>
#include <iostream>
#include <cstdio>
#include <cmath>
#include <vector>
#include <string>
using namespace std;

int n,l;
int cnt;
vector<char> vec;

bool judge()
{
if(vec.size() == 0)
return true;
int m = vec.size();
int i,j;
for(i=1;i<=m/2;i++)
{
for(j=0;j<i;j++)
{
if(vec[m-j-1] != vec[m-i-j-1])
{
break;
}
}
if(j >= i)
return false;
}
return true;
}

void out()
{
for(int i=0;i<vec.size();i++)
{

if(i%4 == 0 && i%64 != 0)
putchar(' ');
else if(i%64 == 0 && i != 0)
puts("");
printf("%c",vec[i]);
}
printf("\n%d\n",vec.size());
}

void dfs()
{
if(judge())
cnt++;
else
return;
if(cnt == n)
{
out();
return;
}
for(char i = 'A';i < 'A' + l;i++)
{
vec.push_back(i);
dfs();
if(cnt == n)
return;
vec.pop_back();
}
}

int main()
{
while(scanf("%d%d",&n,&l) == 2 && n)
{
cnt = -1;
vec.clear();
dfs();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: