题目链接:https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&category=0&problem=995&mosmsg=Submission+received+with+ID+26578658
如果把每个珠子看成点,不好建图。
将每种颜色看成点,每个珠子就对应一条无向边,于是转化成求欧拉回路的问题。
无向图求欧拉回路要注意经过一条边以后,将反向边也标记。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
const int maxn = 5010;
const int maxcolor = 50;
int T, n;
int h[maxcolor+10], cnt = 1;
struct e{
int from, to, id, next;
}e[maxn];
void add(int u, int v, int id){
e[++cnt].to = v;
e[cnt].from = u;
e[cnt].id = id; // 项链的编号
e[cnt].next = h[u];
h[u] = cnt;
}
int vis[maxn], deg[maxcolor+10];
vector<int> path;
void euler(int u){
for(int i = h[u] ; i != -1 ; i = e[i].next){
if(!vis[i]){
vis[i] = 1;
vis[i ^ 1] = 1;
int v = e[i].to;
euler(v);
path.push_back(i);
}
}
}
ll read(){ ll s = 0, f = 1; char ch = getchar(); while(ch < '0' || ch > '9'){ if(ch == '-') f = -1; ch = getchar(); } while(ch >= '0' && ch <= '9'){ s = s * 10 + ch - '0'; ch = getchar(); } return s * f; }
int main(){
int kase = 0;
int flag = 0;
T = read();
while(T--){
if(flag) printf("\n");
flag = 1;
path.clear();
memset(deg, 0, sizeof(deg));
memset(h, -1, sizeof(h)); cnt = 1;
memset(vis, 0, sizeof(vis));
n = read();
int u, v;
int start = -1;
for(int i = 1 ; i <= n ; ++i){
u = read(), v = read();
++deg[u]; ++deg[v];
add(u, v, i); add(v, u, i);
start = u;
}
bool solved = true;
for(int i = 1 ; i <= maxcolor ; ++i){
if(deg[i] % 2 == 1){
solved = false;
break;
}
}
if(solved) euler(start);
printf("Case #%d\n", ++kase);
if(path.size() != n ||e[path[0]].to != e[path[path.size()-1]].from){
solved = false;
}
if(!solved) printf("some beads may be lost\n");
else {
for(int i = path.size() - 1 ; i >= 0 ; --i){
printf("%d %d\n", e[path[i]].from, e[path[i]].to);
}
}
}
return 0;
}