-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdaa_7_1.cpp
More file actions
104 lines (93 loc) · 2.27 KB
/
Copy pathdaa_7_1.cpp
File metadata and controls
104 lines (93 loc) · 2.27 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
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
#include <bits/stdc++.h>
using namespace std;
class info{
public:
int src,dest,weight;
info(int src,int dest,int weight){
this->src = src;
this->dest = dest;
this->weight = weight;
}
};
class compare{
public:
bool operator()(const info &a,const info &b){
return a.weight < b.weight;
}
};
class Graph
{
public:
int v;
vector<list<pair<int,int>>> adj;
Graph(int vertices) : v(vertices), adj(vertices) {};
void addEdge(int u, int v,int w)
{
adj[u].push_back({v,w});
adj[v].push_back({u,w});
}
void display()
{
for (int i = 0; i < v; i++)
{
cout << i << "->";
for (auto it : adj[i])
{
cout << "{"<<it.first << ","<<it.second<<"}";
}
cout << endl;
}
}
};
int find(int u,vector<int>&parent){
if(parent[u] == u)return u;
return parent[u] = find(parent[u],parent);
}
void union_set(int u,int v,vector<int>&parent){
int pu = find(u,parent);
int pv = find(v,parent);
if(pu != pv){
parent[pv] = pu;
}
}
void krushkal(Graph &g){
priority_queue<info,vector<info>,compare>pq;
vector<vector<bool>>visited(g.v,vector<bool>(g.v,false));
for(int i = 0;i< g.v;i++){
for(auto it:g.adj[i]){
if(!visited[i][it.first] && !visited[it.first][i]){
pq.push(info(i,it.first,it.second));
visited[i][it.first] = true;
visited[it.first][i] = true;
}
}
}
vector<int>parent(g.v);
for(int i = 0;i<g.v;i++){
parent[i] = i;
}
int cost = 0;
while(!pq.empty()){
info temp = pq.top();
pq.pop();
if(find(temp.src,parent) != find(temp.dest,parent)){
cout<<temp.src<<"->"<<temp.dest<<endl;
cost += temp.weight;
union_set(temp.src,temp.dest,parent);
}
}
cout<<"total min cost(KRUSHKAL) :"<<cost<<endl;
}
int main()
{
Graph g(5);
g.addEdge(0, 1,10);
g.addEdge(0, 3,30);
g.addEdge(1,2,5);
g.addEdge(2, 3,25);
g.addEdge(3, 4,7);
g.display();
cout<<endl<<endl;
krushkal(g);
return 0;
}