-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday78.cpp
More file actions
60 lines (47 loc) · 1.4 KB
/
day78.cpp
File metadata and controls
60 lines (47 loc) · 1.4 KB
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
#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> pii;
// Function to compute the Manhattan distance between two points
int manhattanDist(const vector<int>& a, const vector<int>& b) {
return abs(a[0] - b[0]) + abs(a[1] - b[1]);
}
// Function to find the Minimum Spanning Tree using Prim's algorithm
int minEffortToConnect(vector<vector<int>>& points) {
int n = points.size();
vector<bool> inMST(n, false);
priority_queue<pii, vector<pii>, greater<pii>> pq;
pq.push({0, 0}); // {cost, index}
int totalEffort = 0;
int edgesUsed = 0;
while (!pq.empty() && edgesUsed < n) {
auto [cost, u] = pq.top();
pq.pop();
if (inMST[u]) continue;
inMST[u] = true;
totalEffort += cost;
edgesUsed++;
for (int v = 0; v < n; v++) {
if (!inMST[v]) {
int dist = manhattanDist(points[u], points[v]);
pq.push({dist, v});
}
}
}
return totalEffort;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int T;
cin >> T;
while (T--) {
int n;
cin >> n;
vector<vector<int>> points(n, vector<int>(2));
for (int i = 0; i < n; i++) {
cin >> points[i][0] >> points[i][1];
}
cout << minEffortToConnect(points) << "\n";
}
return 0;
}