-
Notifications
You must be signed in to change notification settings - Fork 697
/
Euler Path.cpp
64 lines (58 loc) · 1.18 KB
/
Euler Path.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
struct DirectedEulerPath
{
int n;
vector<vector<int> > g;
vector<int> path;
void init(int _n)
{
n = _n;
g = vector<vector<int> > (n + 1, vector<int> ());
path.clear();
}
void add_edge(int u, int v)
{
g[u].push_back(v);
}
void dfs(int u)
{
while(g[u].size())
{
int v = g[u].back();
g[u].pop_back();
dfs(v);
}
path.push_back(u);
}
bool getPath()
{
int ctEdges = 0;
vector<int> outDeg, inDeg;
outDeg = inDeg = vector<int> (n + 1, 0);
for(int i = 1; i <= n; i++)
{
ctEdges += g[i].size();
outDeg[i] += g[i].size();
for(auto &u:g[i])
inDeg[u]++;
}
int ctMiddle = 0, src = 1;
for(int i = 1; i <= n; i++)
{
if(abs(inDeg[i] - outDeg[i]) > 1)
return 0;
if(inDeg[i] == outDeg[i])
ctMiddle++;
if(outDeg[i] > inDeg[i])
src = i;
}
if(ctMiddle != n && ctMiddle + 2 != n)
return 0;
dfs(src);
reverse(path.begin(), path.end());
return (path.size() == ctEdges + 1);
}
};
//Problem 1: https://csacademy.com/contest/round-48/task/matching-substrings/
//Solution 1: http://p.ip.fi/WTb7
//Problem 2: https://codeforces.com/contest/508/problem/D
//Solution 2: https://codeforces.com/contest/508/submission/86976956