Title
Portal AcWing 400 Taiko Master
answer
Length is KKK of01010 1 string total2 K 2^K2K types, need to move clockwise on the ring as much as possible to traverse different01 010 1 string, and return to the initial string. WillKKK long01 01The 0 1 string is regarded as an edge, and the weight is01 010 The last digit of the string of 1 will be the01 01represented by the side0 1 string ofK − 1 K-1K−1 long prefix is considered as a point. Each point has2 2With two outgoing edges and incoming edges, there are Euler circuits of the directed graph. Take the point0 00 is the starting point to solve the Euler circuit. In order to ensure the minimum lexicographic order, recursively start from the edge with the smaller weight. Total time complexityO (2 K) O(2^K)O ( 2K)。
#include <bits/stdc++.h>
using namespace std;
const int maxk = 12, maxn = 1 << maxk, maxm = maxn << 1;
int K, nr, res[maxn];
int tot, head[maxn], to[maxm], nxt[maxm], cost[maxm];
bool vs[maxn];
inline void add(int x, int y, int z)
{
to[++tot] = y, cost[tot] = z, nxt[tot] = head[x], head[x] = tot;
}
void euler(int x)
{
for (int &i = head[x], y, z; i;)
{
y = to[i], z = cost[i], i = nxt[i];
euler(y);
res[++nr] = z;
}
}
int main()
{
scanf("%d", &K);
int t = 1 << (K - 1);
for (int i = 0; i < t; ++i)
{
int j = (i << 1) & (t - 1);
add(i, j | 1, 1), add(i, j, 0);
}
euler(0);
printf("%d ", 1 << K);
for (int i = 1; i < K; ++i)
putchar('0');
while (nr >= K)
putchar(res[nr--] + '0');
putchar('\n');
return 0;
}