Original title: Https://uva.onlinejudge.org/external/1/129.pdf
Generation of nth "difficult strings" in dictionary order
"Difficult strings" refer to strings of shapes such as Abab, ABCABC, Cdfgzefgze, and they all have adjacent repeating substrings.
The range of letters is L, both ' a ' to ' a ' + L
Analysis: This is basically a question of generating permutations. The difficulty is how we judge that the current generated string is a "difficult string"
We first use recursion to generate strings from small to large in dictionary order, so every time we deal with the previous "difficult string",
Satisfies both no adjacent repeating substrings. So how efficiently do we judge whether the newly added letters will make it not satisfy the "difficult strings" condition?
Judging method :
If the last letter equals the second letter, then it is not a difficult string, return False
From right to left, find the first letter with the letter at the end, because it could be the end of the adjacent repeating string.
Then take the found letter as the center point, determine whether the left and right strings are equal, return false
Repeat the above steps
So the algorithm time complexity is O (n^2)
Because n <= 80
So it's totally enough.
1#include <cstdio>2#include <cstring>3 using namespacestd;4 Const intMAXN = the+5;5 intSOL[MAXN], L, N, CNT, depth;6 BOOLstop;7 8 BOOLCheckintIndexintCHR) {9 if(Index >0) {Ten if(CHR = = Sol[index-1])return false; One inti = index-1; A while(I >=0) { - while(I >=0&& sol[i]! = CHR) i--; - if(I >=0&& Sol[i] = = CHR && i *2+1>=index) { the BOOLsame =1; - for(intj = Index-1; J > i; j--) - if(Sol[j]! = Sol[j-index + i]) same =0; - if(same)return false; + } -i--; + } A } at return true; - } - - voidNEXT_STR (intDEP) { - if(CNT = =N) { -Stop =1; in for(inti =0; I < DEP; i++) { - if(I && i% -==0) Putchar ('\ n'); to Else if(I && i%4==0) Putchar (' '); +printf"%c",Char(Sol[i] +'A')); - } thedepth =DEP; *Putchar ('\ n'); $ return;Panax Notoginseng } - for(inti =0; i < L; i++) { the if(stop)return; + if(check (DEP, i)) { ASOL[DEP] =i; thecnt++; +NEXT_STR (DEP +1); - } $ } $ } - - intMain () { the while(SCANF ("%d%d", &n, &l) = =2&&N) { -Stop =0; CNT = depth =0;WuyiNEXT_STR (0); theprintf"%d\n", depth); - } Wu return 0; -}
Krypton Factor Difficult string-uva 129 (backtracking)