无向图欧拉回路 欧拉通路
#include <cstdio> #include <cstring> using namespace std; struct edge { int v, next, b, id; }e[210]; int vis[210]; int first[10], cnt; int ans[210], len; int f[10]; int find(int x) { if(x != f[x]) return f[x] = find(f[x]); return f[x]; } void AddEdge(int u, int v, int id) { e[cnt].id = id; e[cnt].b = 0; e[cnt].v = v; e[cnt].next = first[u]; first[u] = cnt++; e[cnt].id = id; e[cnt].b = 1; e[cnt].v = u; e[cnt].next = first[v]; first[v] = cnt++; } void dfs(int u) { for(int i = first[u]; i != -1; i = e[i].next) { if(!vis[i]) { vis[i] = 1; vis[i^1] = 1; dfs(e[i].v); ans[len++] = i; } } } int main() { int n; scanf("%d", &n); memset(first, -1, sizeof(first)); cnt = 0; int b[10] = {0}, s1 = 0, s2 = 0; for(int i = 0; i <= 6; i++) f[i] = i; for(int i = 1; i <= n; i++) { int u, v; scanf("%d %d", &u, &v); AddEdge(u, v, i); if(!b[u]) { s1++; b[u] = 1; } else b[u]++; if(!b[v]) { s1++; b[v] = 1; } else b[v]++; int x = find(u), y = find(v); if(x != y) { f[x] = y; s2++; } } int rt = -1, sum = 0; len = 0; for(int i = 0; i <= 6; i++) { if(b[i]&1) { sum++; rt = i; } } if(s1 - 1 != s2) { puts("No solution"); } else if(sum == 2) { dfs(rt); for(int i = len-1; i >= 0; i--) { int x = ans[i]; if(e[x].b) printf("%d -\n", e[x].id); else printf("%d +\n", e[x].id); } } else if(!sum) { for(int i = 0; i <= 6; i++) { if(b[i]) { dfs(i); break; } } for(int i = len-1; i >= 0; i--) { int x = ans[i]; if(e[x].b) printf("%d -\n", e[x].id); else printf("%d +\n", e[x].id); } } else puts("No solution"); return 0; }
时间: 2024-12-15 18:30:17