The main topic: a string composed of letters A to Z, wherein two substrings are exactly the same as the easy string, which is called the difficult string. Find the nth difficult string consisting of the first L letters.
Problem analysis: Simple backtracking, but it's tricky to tell if there are duplicate substrings. For reference to the eight Queens question, we only judge whether there are continuous substrings after the addition of characters. This is done by enumerating the lengths of the object to enumerate the substrings with the newly added characters as tails to see if they are duplicated.
The code is as follows:
# include<iostream># include<cstdio># include<cstring># include<algorithm>using namespace Std;int n,k,cnt,path[1000];void dfs (int cur) {if (cur>81) return; if (cnt++==n) {for (int i=0;i<cur;++i) {printf ("%c", char (path[i]+ ' A ')); if (i%4==3&&i!=cur-1) {if (i%64==63) printf ("\ n"); else printf (""); }} printf ("\n%d\n", cur); return; } for (int i=0;i<k;++i) {path[cur]=i; int flag=1; for (int j=1;j*2<=cur+1;++j) {int ok=1; for (int l=0;l<j;++l) if (Path[cur-l]!=path[cur-l-j]) {ok=0; Break } if (ok) {flag=0; Break }} if (flag) DFS (CUR+1); if (cnt>n) return; }}int Main () {while (scanf ("%d%d", &n, &k) && (n+k)) {cnt=0; DFS (0); } return 0;}
UVA-129 Krypton Factor (backtracking)