I made a water question yesterday, and today it is a relatively water application.
The beads of n necklaces are given. There are two colors at both ends of the beads. The adjacent beads on the necklace must match the color to determine whether they can be pieced together into a one-day necklace.
It was quite watery, but at first I thought of the entire necklace as a dot, and then I used dfs to find it. The result timed out.
Later, I glanced at the question and found that the color was treated as a dot, and a bead was a path. In this way, I could get an undirected graph and then judge the Euler loop.
By default, the beads are connected, so you do not need to judge the connectivity. Then, judge whether the degree of the node is an even number, that is, whether it is an Euler loop. If so, use the deep search to output the order of beads. Deep Search output should be put after recursion and output in reverse order. Otherwise, errors may occur. For details, refer to Titanium's blog. (Orz)
Code:
#include <cstdio> #include <cstring> const int maxn = 51; int t, n; int id[maxn], g[maxn][maxn]; void euler(int u) { for (int i = 1; i <= 50; i++) if (g[u][i]) { g[u][i]--; g[i][u]--; euler(i); printf("%d %d\n", i, u); } } int main() { scanf("%d", &t); int a, b; for (int cas = 1; cas <= t; cas++) { scanf("%d", &n); memset(id, 0, sizeof(id)); memset(g, 0, sizeof(g)); for (int i = 0; i < n; i++) { scanf("%d%d", &a, &b); g[a][b]++; g[b][a]++; id[a]++; id[b]++; } int i; for (i = 1; i <= 50; i++) if (id[i] % 2) break; if (cas > 1) printf("\n"); printf("Case #%d\n", cas); if (i <= 50) printf("some beads may be lost\n"); else for (i = 0; i <= 50; i++) euler(i); }//for return 0; } #include <cstdio>#include <cstring>const int maxn = 51;int t, n;int id[maxn], g[maxn][maxn];void euler(int u) {for (int i = 1; i <= 50; i++) if (g[u][i]) {g[u][i]--;g[i][u]--;euler(i);printf("%d %d\n", i, u);}}int main() {scanf("%d", &t);int a, b;for (int cas = 1; cas <= t; cas++) {scanf("%d", &n);memset(id, 0, sizeof(id));memset(g, 0, sizeof(g));for (int i = 0; i < n; i++) {scanf("%d%d", &a, &b);g[a][b]++; g[b][a]++;id[a]++; id[b]++;}int i;for (i = 1; i <= 50; i++)if (id[i] % 2)break;if (cas > 1)printf("\n");printf("Case #%d\n", cas);if (i <= 50)printf("some beads may be lost\n");elsefor (i = 0; i <= 50; i++)euler(i);}//forreturn 0;}