总算AC了,好帅气的算法,同时解决了自环跟非连通,一种自下向上找环的算法过程,这里把欧拉回路讲得很清楚,赞。
#include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <map>
#include <string.h>
using namespace std; class Edge {
public:
int no, u, v;
char d;
Edge() {
no = u = v = d = -;
}
Edge reverse() {
Edge rev;
rev.no = no;
rev.u = v;
rev.v = u;
rev.d = d == '+' ? '-' : '+';
return rev;
}
}; class Graph {
private:
map<int, int> u2i;
vector<vector<Edge> > G;
int deg[], n, no, use[], vUse[];
vector<Edge> solution;
public:
Graph(vector<Edge>& edges) {
n = edges.size();
makeU2I(edges);
memset(deg, , sizeof(deg));
G.clear();
G.resize(no);
for (int i = ; i < edges.size(); i++) {
G[u2i[edges[i].u]].push_back(edges[i]);
G[u2i[edges[i].v]].push_back(edges[i].reverse());
deg[u2i[edges[i].u]]++;
deg[u2i[edges[i].v]]++;
}
}
void makeU2I(vector<Edge>& edges) {
u2i.clear();
for (int i = ; i < edges.size(); i++) {
u2i[edges[i].u] = u2i[edges[i].v] = ;
}
no = ;
for (map<int, int>::iterator it = u2i.begin(); it != u2i.end(); it++) {
it->second = no++;
}
}
int solve() {
int beg = -, end = -;
for (int i = ; i < no; i++) {
if (deg[i] & ) {
if (beg == -) {
beg = i;
} else if (end == -) {
end = i;
} else {
return -;
}
}
}
if (beg == -) {
beg = ;
}
memset(use, , sizeof(use));
Edge begEdge;
dfs(beg, -, begEdge);
if (solution.size() < n) {
// 判连通
return -;
}
return ;
}
void dfs(int u, int sign, Edge lastEdge) {
for (int i = ; i < G[u].size(); i++) {
if (use[G[u][i].no] == ) {
use[G[u][i].no] = ;
dfs(u2i[G[u][i].v], , G[u][i]);
}
} if (sign > ) {
solution.push_back(lastEdge);
}
}
void getSolution() {
for (int i = solution.size() - ; i >= ; i--) {
printf("%d %c\n", solution[i].no, solution[i].d);
}
}
}; int main()
{
int n;
scanf("%d", &n); vector<Edge> edges;
for (int i = ; i < n; i++) {
int a, b;
scanf("%d%d", &a, &b); Edge e;
e.no = i + ;
e.u = a; e.v = b;
e.d = '+'; edges.push_back(e);
} Graph graph(edges);
if (graph.solve() == -) {
printf("No solution\n");
} else {
graph.getSolution();
} //system("pause");
}