-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweek 8_Q3
92 lines (83 loc) · 1.58 KB
/
week 8_Q3
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
#include<bits/stdc++.h>
using namespace std;
bool cmp(vector<int> &a,vector<int> &b)
{
return a[2]>b[2];
}
int findParent(vector<int> &parent,int node)
{
if(parent[node]==node)
return node;
return parent[node]=findParent(parent,parent[node]);
}
void unionSet(int u,int v,vector<int> &parent,vector<int> &rank)
{
u=findParent(parent,u);
v=findParent(parent,v);
if(rank[u]>rank[v])
{
parent[v]=u;
}
else if(rank[v]>rank[u])
{
parent[u]=v;
}
else
{
parent[v]=u;
rank[u]++;
}
}
int minspanning(vector<vector<int>> &graph,int n)
{
sort(graph.begin(),graph.end(),cmp);
vector<int> parent(n);
vector<int> rank(n);
for(int i=0;i<n;i++)
{
parent[i]=i;
rank[i]=0;
}
int minweight=0;
for(auto i : graph)
{
int u=findParent(parent,i[0]);
int v=findParent(parent,i[1]);
int w=i[2];
if(u!=v)
{
minweight += w;
unionSet(u,v,parent,rank);
}
}
return minweight;
}
int main()
{
int n;
cin>>n;
int arr[n][n];
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
int num;
cin>>num;
arr[i][j]=num;
}
}
vector<vector<int>> graph;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(arr[i][j]!=0)
{
graph.push_back({i+1,j+1,arr[i][j]});
}
}
}
int result=minspanning(graph,n);
cout<<"Maximum spanning weight : "<<result;
return 0;
}