-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path10000 - Longest Paths.cpp
90 lines (65 loc) · 1.78 KB
/
10000 - Longest Paths.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
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
explicit Node(int id) {
this->id = id;
}
int id;
vector<Node*> children;
};
bool compareNodes(Node *a, Node *b) {
return (a->id < b->id);
}
int main() {
int caseNumber = 1;
int n;
do {
cin >> n;
if (n == 0) {
break;
}
vector<Node*> nodes;
nodes.reserve(n + 1);
for (int i = 1; i <= n; i++) {
nodes[i] = new Node(i);
}
int s;
cin >> s;
int p, q;
cin >> p >> q;
while (p != 0 && q != 0) {
nodes[p]->children.push_back(nodes[q]);
cin >> p >> q;
}
vector<Node*> current;
vector<Node*> next;
Node *last = nodes[s];
current.push_back(last);
int count = 0;
while (!current.empty()) {
vector<bool> visits(n + 1, false);
sort(current.begin(), current.end(), compareNodes);
for (int i = current.size() - 1; i >= 0; i--) {
Node* node = current[i];
last = node;
for (auto& child : node->children) {
if (!visits[child->id]) {
visits[child->id] = true;
next.push_back(child);
}
}
}
current.clear();
swap(current, next);
if (!current.empty())
count++;
}
cout << "Case " << caseNumber++ << ": The longest path from " << s << " has length " << count << ", finishing at " << last->id << "." << endl;
cout << endl;
for (int i = 1; i <= n; i++) {
delete nodes[i];
}
} while (n != 0);
return 0;
}