-
Notifications
You must be signed in to change notification settings - Fork 1
/
EulerianPathAndCycle.cpp
74 lines (74 loc) · 1.38 KB
/
EulerianPathAndCycle.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
typedef vector<int> VI;
typedef vector<VI> VVI;
struct EulerianPath {
struct Edge{
int u,v,used;
int getV(int _u){
return _u == u ? v : u;
}
};
bool directed;
VVI adj;
vector<Edge> E;
VI cId, outDeg, inDeg;
int N;
EulerianPath(int N, int directed = false){
this->directed = directed;
this->N = N;
adj = VVI(N);
cId = VI(N);
outDeg= VI(N);
inDeg = VI(N);
}
void addEdge(int u,int v){
Edge e = (Edge){ u, v, 0 };
adj[u].push_back(E.size());
outDeg[u]++;
inDeg[v]++;
if(!directed){
adj[v].push_back(E.size());
outDeg[v]++;
inDeg[u]++;
}
E.push_back(e);
}
vector<int> getEulerPath(){
int st = -1 , cnt = 0;
for(int i = 0; i < N; ++i){
if(st == -1 && outDeg[i])
st = i;
if(directed){
int d = outDeg[i] - inDeg[i];
if(d > 1)return vector<int>();
if(d ==1)st = i, cnt++;
if(cnt>=2)return vector<int>();
}else{
int d = outDeg[i];
if(d%2!=0)st = i, cnt++;
if(cnt> 2)return vector<int>();
}
}
stack<int> STK;
STK.push(st);
vector<int> ret;
while(STK.size()){
int u = STK.top();
bool found = false;
while(cId[u] < adj[u].size()){
Edge &e = E[adj[u][cId[u]++]];
if(e.used)continue;
e.used = true;
int v = e.getV(u);
found = true;
STK.push(v);
break;
}
if(!found){
STK.pop();
ret.push_back(u);
}
}
reverse(ret.begin(),ret.end());
return ret;
}
};