forked from izanbf1803/Codingame
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTeads Sponsored Contest.cpp
123 lines (93 loc) · 2.83 KB
/
Teads Sponsored Contest.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
114
115
116
117
118
119
120
121
122
123
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <map>
#include <queue>
#include <math.h>
using namespace std;
typedef struct {
vector<int> edges;
bool explored;
int depth;
int id;
} Node;
float max_depth = 0;
int starter_id;
Node* create_node(int id)
{
Node* node = new Node;
node->edges = vector<int>();
node->depth = 0;
node->explored = false;
node->id = id;
return node;
}
void prepare_graph(map<int, Node*>& graph)
{
Node* current;
for (map<int, Node*>::iterator it = graph.begin(); it != graph.end(); it++) {
current = graph[it->first];
current->explored = false;
current->depth = 2147483647;
}
}
void BFS(
map<int, Node*>& graph,
int s_id)
{
prepare_graph(graph);
Node* s = graph[s_id];
s->explored = true;
s->depth = 0;
queue<int> next;
next.push(s->id);
Node *current, *x;
while (not next.empty()) {
x = graph[next.front()];
next.pop();
for (int i = 0; i < x->edges.size(); i++) { // iterate x node edges
//cerr << i << " i" << endl;
//cerr << "edge: " << x->edges[i] << endl;
current = graph[x->edges[i]];
if (not current->explored) {
current->explored = true;
current->depth = x->depth + 1;
next.push(current->id); // Push current node to queue(next)
}
}
}
for (map<int, Node*>::iterator it = graph.begin(); it != graph.end(); it++) {
current = graph[it->first];
//cerr << current->id << " depth = " << current->depth << endl;
if (current->depth > max_depth) {
max_depth = current->depth;
starter_id = current->id;
}
//if (current->depth == max_depth) starter_id = current->id;
}
}
int main()
{
int n, xi, yi; // the number of adjacency relations
cin >> n; cin.ignore();
map<int, Node*> graph;
for (int i = 0; i < n; i++) {
// int xi; // the ID of a person which is adjacent to yi
// int yi; // the ID of a person which is adjacent to xi
cin >> xi >> yi; cin.ignore();
if (graph.find(xi) == graph.end())
graph[xi] = create_node(xi);
if (graph.find(yi) == graph.end())
graph[yi] = create_node(yi);
graph[xi]->edges.push_back(yi);
graph[yi]->edges.push_back(xi);
}
starter_id = xi;
BFS(graph, starter_id);
BFS(graph, starter_id);
//cerr << "max_depth = " << max_depth << endl;
cout << ceil(max_depth / 2) << endl;
for (map<int, Node*>::iterator it = graph.begin(); it != graph.end(); it++)
delete graph[it->first];
}