-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrim.cpp
More file actions
34 lines (30 loc) · 696 Bytes
/
Prim.cpp
File metadata and controls
34 lines (30 loc) · 696 Bytes
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
int vis[101] = {0};
vector<vector<edg>>adj;
struct edg {
int w, to;
bool operator<(const edg &e) const {
return e.w < w;
}
};
int prim() {
priority_queue<edg> pq;
pq.push({0, 1});
int total = 0;
while (!pq.empty()) {
int node = pq.top().to;
int w = pq.top().w;
pq.pop();
if (vis[node])continue;
vis[node] = 1;
total += w;
if (node != 1)edges.push_back({w, node});
for (int i = 0; i < adj[node].size(); ++i) {
edg v = adj[node][i];
if (!vis[v.to]) {
pq.push(v);
}
}
}
if (edges.size() != n - 1)return -1;
return total;
}