Hdu 1627 Krypton Factor (DFS/生成排列)
http://acm.hdu.edu.cn/showproblem.php?pid=1627
暴力解,深度遍历生成排列判断是否满足条件,满足继续深度递归,反之跳过执行下一个
1 #include <cstdio> 2 #include <cstring> 3 #include <iostream> 4 #include <cmath> 5 #include <algorithm> 6 using namespace std; 7 int n,l,c=0,k; 8 bool is_p(string str) //判断该串是否重复 9 { 10 int i,j,s=1,a; 11 for(s=1; s<=str.length()/2; s++) 12 { 13 a=1; 14 for(i=str.length()-1,j=i-s; i>=0&&j>=0&&a<=s; i--,j--,a++) 15 { 16 if(str[i]!=str[j]) break; 17 } 18 if(a>s) return false; 19 } 20 return true; 21 } 22 string f(int leth,string str) 23 { 24 string cp; 25 for(int i=0; i<l&&!k; i++) //DFS遍历每个元素 26 { 27 cp=str; 28 cp+=('A'+i); 29 if(is_p(cp)) 30 { 31 //cout<<"c:"<<c<<" str: "<<cp<<"\n"; 32 c++; 33 if(c==n) 34 { 35 k=1; 36 return cp; 37 } 38 cp=f(leth+1,cp); 39 } 40 } 41 return cp; 42 } 43 int main() 44 { 45 while(scanf("%d%d",&n,&l)==2&&(n||l)) 46 { 47 k=0;c=0; 48 string str=f(1,""); 49 int a=str.length(); 50 int s=0; 51 for(int i=0; i<a; i++) 52 { 53 cout<<str[i]; 54 if((i+1)%4==0) 55 { 56 s++; 57 if(s==16) printf("\n"); 58 else if(i!=a-1)printf(" "); 59 } 60 } 61 printf("\n%d\n",a); 62 } 63 return 0; 64 }

浙公网安备 33010602011771号