UVa129 - Krypton Factor 不错的DFS入门题
2015-01-29 23:59
387 查看
题意 一个字符串被称为容易串,指其中有相邻的两个相同的子串,反之为困难串。问你由前L个字符组成的字典序第k小的困难串。保证答案串长不超过80。
思路 难点在于如何判断当前串是否为困难串,整串比较O(n^3),但如果用dfs,每次只需要判断新加入的字母会不会使字符串为困难串即可,通过枚举不同长度的后缀即可,复杂度O(n^2)。是容易串就做可行性剪枝。
感觉这题非常适合dfs,整个就是为其设计的感觉,是入门dfs的好题~
思路 难点在于如何判断当前串是否为困难串,整串比较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; }
相关文章推荐
- Krypton Factor UVA - 129(DFS回溯)
- UVa 129 - Krypton Factor(DFS+回溯)
- UVA--129 - Krypton Factor(神奇的if判别式引发的PE) 回溯
- UVa 129:Krypton Factor(回溯)
- 紫书章七例五 Krypton Factor UVA - 129(dfs)判断一个字符串中是否包含两个相邻子串
- 紫书章七例五 Krypton Factor UVA - 129(dfs)判断一个字符串中是否包含两个相邻子串
- Krypton Factor UVA - 129
- 紫书章七例五 Krypton Factor UVA - 129(dfs)判断一个字符串中是否包含两个相邻子串
- Krypton Factor UVA - 129
- 紫书章七例五 Krypton Factor UVA - 129(dfs)判断一个字符串中是否包含两个相邻子串
- 129 - Krypton Factor(dfs回溯)
- 困难的串(Krypton Factor,UVa 129)
- 困难的串(Krypton Factor,UVa 129)
- Uva 129 Krypton Factor(困难的串)
- UVa 129 Krypton Factor (回溯好题)
- 紫书章七例五 Krypton Factor UVA - 129(dfs)判断一个字符串中是否包含两个相邻子串
- uva 129 Krypton Factor
- 困难的串(Krypton Factor,UVa129)
- 紫书章七例五 Krypton Factor UVA - 129(dfs)判断一个字符串中是否包含两个相邻子串
- 紫书章七例五 Krypton Factor UVA - 129(dfs)判断一个字符串中是否包含两个相邻子串