-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy path629.minimum-spanning-tree.cpp
124 lines (108 loc) · 2.71 KB
/
629.minimum-spanning-tree.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
124
/**
* Definition for a Connection.
* class Connection {
* public:
* string city1, city2;
* int cost;
* Connection(string& city1, string& city2, int cost) {
* this->city1 = city1;
* this->city2 = city2;
* this->cost = cost;
* }
*/
class UnionFind {
vector<int> graph;
int size;
public:
UnionFind(int n)
{
graph.resize(n);
size = n;
for(int i = 0; i < n; ++i)
{
graph[i] = i;
}
}
int find(int node)
{
if (graph[node] == node)
{
return node;
}
graph[node] = find(graph[node]);
return graph[node];
}
bool query(int a, int b)
{
return find(a) == find(b);
}
void connect(int a, int b)
{
int root_a = find(a);
int root_b = find(b);
if (root_a != root_b)
{
graph[root_a] = root_b;
size--;
}
}
bool allConnected()
{
return size == 1;
}
};
class Solution {
public:
/**
* @param connections given a list of connections include two cities and cost
* @return a list of connections from results
*/
vector<Connection> lowestCost(vector<Connection>& connections) {
// Write your code here
//sort according to cost
auto comp = [](Connection& x, Connection& y){
if (x.cost != y.cost){
return x.cost < y.cost;
}
else if(x.city1 != y.city1)
{
return x.city1 < y.city1;
}
else
{
return x.city2 < y.city2;
}
};
sort(connections.begin(), connections.end(), comp);
// map city
int count = 0;
int size = connections.size();
unordered_map<string, int> cityMap;
for(int i = 0; i < size; ++i)
{
Connection conn = connections[i];
if (cityMap.count(conn.city1) == 0)
{
cityMap[conn.city1] = count++;
}
if (cityMap.count(conn.city2) == 0)
{
cityMap[conn.city2] = count++;
}
}
UnionFind uf(count);
vector<Connection> res;
for(int i = 0; i < size; ++i)
{
Connection conn = connections[i];
int city1 = cityMap[conn.city1];
int city2 = cityMap[conn.city2];
if(!uf.query(city1, city2))
{
uf.connect(city1, city2);
res.push_back(conn);
}
}
return uf.allConnected() ? res: vector<Connection>();
}
};