-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathprim.cpp
More file actions
76 lines (71 loc) · 1.42 KB
/
prim.cpp
File metadata and controls
76 lines (71 loc) · 1.42 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
#include <iostream>
#include <string>
#include <queue>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
#define MAX 100
const int INF = 1e9;
vector <pair<int, int>>graph[MAX];
vector<int>dist(MAX, INF);
int path[MAX];
bool visited[MAX];
int N;
void printMST()
{
int ans = 0;
for (int i = 0; i < N; i++)
{
if (path[i] == -1)
continue;
ans += dist[i];
cout << path[i] << " - " << i << ": " << dist[i] << endl;
}
cout << "Weight of MST: " << ans << endl;
}
struct option {
bool operator()(const pair <int, int>& a, const pair<int, int>& b)const {
return a.second > b.second;
}
};
void Prims(int src)
{
priority_queue<pair<int, int>, vector<pair<int, int>>, option>pq;
pq.push(make_pair(src, 0));
dist[src] = 0;
while (!pq.empty())
{
int u = pq.top().first;
pq.pop();
visited[u] = true;
for (int i = 0; i < graph[u].size(); i++)
{
int v = graph[u][i].first;
int w = graph[u][i].second;
pair<int, int > neighbor = graph[u][i];
if (!visited[v] && dist[v] > w)
{
dist[v] = w;
pq.push(make_pair(v, w));
path[v] = u;
}
}
}
}
int main()
{
int M, u, v, w;
cin >> N >> M;
memset(path, -1, sizeof(path));
for (int i = 0; i < M; i++)
{
cin >> u >> v >> w;
graph[u].push_back(make_pair(v, w));
graph[v].push_back(make_pair(u, w));
}
int s = 0;
Prims(s);
printMST();
return 0;
}