-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path4neo.cpp
113 lines (96 loc) · 2.29 KB
/
4neo.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include <iostream>
#include <vector>
#include <queue>
#include <map>
#include <algorithm>
#include "tokenizer.h"
#include "graph.h"
using namespace std;
template<typename T>
void resizeFill(int count, vector<T>& v, const T& val)
{
v.resize(count);
fill(v.begin(), v.end(), val);
}
class TopoGraph: public Graph<string>
{
public:
vector<NodeIndex> topoSort()
{
int nodeCount = _nodeNames.size();
resetData();
vector<NodeIndex> solvedNodes;
int curIndex = 0;
for (int i = 0; i < nodeCount; i++)
{
if (inDegrees[i] == 0)
solvedNodes.push_back(i);
}
while (solvedNodes.size() < nodeCount && curIndex < solvedNodes.size())
{
NodeIndex curNode = solvedNodes[curIndex++];
for (auto edge: _edgeWeights[curNode])
{
if (--inDegrees[edge.first] == 0)
solvedNodes.push_back(edge.first);
}
}
return solvedNodes;
}
private:
void resetData()
{
int nodeCount = _nodeNames.size();
resizeFill(nodeCount, inDegrees, 0);
for (int i = 0; i < nodeCount; i++)
{
for (auto edge: _edgeWeights[i])
{
inDegrees[edge.first]++;
}
}
}
vector<NodeIndex> inDegrees;
};
TopoGraph graph;
bool parseGraph(const string& line)
{
Tokenizer tokenizer(line, "-> \t\n\r\b");
string token = tokenizer.nextToken();
if (token.length() == 0)
return false;
string start = token;
token = tokenizer.nextToken();
if (token.length() == 0)
return false;
string end = token;
graph.addEdge(start, end, 1);
return true;
}
void solve()
{
auto nodes = graph.topoSort();
if (nodes.size() == 0)
return;
if (nodes.size() != graph.getNodeCount())
{
cout << "Rings!" << endl;
return;
}
cout << graph.getNodeName(nodes[0]);
for (int i = 1; i < nodes.size(); i++)
{
cout << "->" << graph.getNodeName(nodes[i]);
}
cout << endl;
}
int main()
{
string line;
do
{
getline(cin, line);
} while (parseGraph(line));
solve();
return 0;
}