-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleet1584.cpp
85 lines (76 loc) · 1.73 KB
/
leet1584.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
#include <stdio.h>
#include <string.h>
#include <cstring>
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include <numeric>
#include <string>
#include <cmath>
#include <functional>
#include <cmath>
#include <set>
#include <map>
#include <assert.h>
#include <stack>
#include <unordered_map>
using namespace std;
struct Edge{
int u,v;
int w;
Edge(int x,int y,int z):u(x),v(y),w(z){}
bool operator< (const Edge& e) const
{
return w<e.w;
}
};
class Solution {
vector<int> parent;
public:
int find_parent(int id)
{
return parent[id]==id?id:find_parent(parent[id]);
}
void unify(int x,int y)
{
parent[find_parent(x)] = y;
}
int minCostConnectPoints(vector<vector<int>>& points) {
int N = points.size();
vector<Edge> vec;
parent.resize(N);
for(int i=0;i<N;i++)
parent[i] = i;
for(int i=0;i<points.size();i++)
{
for(int j=i+1;j<points.size();j++)
{
int dist = abs(points[i][0]-points[j][0])+abs(points[i][1]-points[j][1]);
//link[i][j] = dist;
//link[j][i] = dist;
Edge edge(i,j,dist);
vec.emplace_back(edge);
}
}
sort(vec.begin(),vec.end());
int re = 0;
for(auto e:vec)
{
int u = e.u;
int v = e.v;
if(find_parent(u)!=find_parent(v))
{unify(u,v);
re += e.w;
}
}
return re;
}
};
int main()
{
vector<vector<int>> t = {{0,0},{2,2},{3,10},{5,2},{7,0}};
Solution sol;
sol.minCostConnectPoints(t);
return 0;
}