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
| #include <iostream> #include <cstdio> #include <queue> #include <cstring> #define maxn 5010 #define maxm 200010 #define cQ const Queue using namespace std;
int n, m;
struct Edge { int to, next, w; } e[maxm * 2]; int c1, head[maxn]; inline void add_edge(int u, int v, int w) { e[c1].to = v; e[c1].w = w; e[c1].next = head[u]; head[u] = c1++; }
struct Queue { int k, v;
Queue() {} Queue(int _k, int _v) { k = _k; v = _v; }
friend bool operator < (cQ &u, cQ &v) { return u.v > v.v; } }; int dis[maxn], s, mst; bool vis[maxn]; priority_queue<Queue> Q; void Prim() { memset(dis, 127, sizeof dis); dis[s] = 0; Q.push(Queue(s, 0)); while (!Q.empty()) { int u = Q.top().k, _w = Q.top().v; Q.pop(); if (vis[u]) continue; vis[u] = 1; mst += _w; for (int i = head[u]; ~i; i = e[i].next) { int v = e[i].to, w = e[i].w; if (dis[v] > w) { dis[v] = w; Q.push(Queue(v, dis[v])); } } } }
int main() { memset(head, -1, sizeof head); cin >> n >> m; for (int i = 1; i <= m; ++i) { int x, y, z; scanf("%d%d%d", &x, &y, &z); add_edge(x, y, z); add_edge(y, x, z); } s = 1; Prim(); cout << mst << endl; return 0; }
|