hihocoder 第二十九周 堆优化的Prim算法

又深刻理解了一遍prim和dijkstra算法,感觉蛮棒的~

第一次自己用邻接表写,just soso~ 啊哈~

一开始被优先队列,重载运算符给卡住了~ 蛋疼~

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstdlib>
 4 #include<cstring>
 5 #include<string>
 6 #include<queue>
 7 #include<algorithm>
 8 #include<map>
 9 #include<iomanip>
10 #include<climits>
11 #include<string.h>
12 #include<stdlib.h>
13 #include<vector>
14 #define INF 1e7
15 #define MAXN 111111
16 using namespace std;
17 
18 
19 struct node{
20     int v, w;
21     bool operator < (const node& a) const {
22         return w > a.w;
23     }
24 };
25 
26 vector<node> G[MAXN];
27 bool vis[MAXN];
28 int dis[MAXN];
29 int n, m;
30 priority_queue<node> q;
31 
32 
33 void Prim(node s)
34 {
35     memset(vis, 0, sizeof(vis));
36     for (int i = 0; i <= n; ++i) dis[i] = INF;
37     while (!q.empty())  q.pop();
38     int ans = 0;
39     q.push(s);
40     while (!q.empty()) {
41         node u = q.top();
42         q.pop();
43         if (vis[u.v]) continue;
44         vis[u.v] = true;
45         ans += u.w;
46         //cout << ans << endl;
47         for (int i = 0; i < G[u.v].size(); ++i) {
48             int v = G[u.v][i].v;
49             if (!vis[v] && dis[v] > G[u.v][i].w) {
50                 dis[v] = G[u.v][i].w;
51                 q.push({ v, dis[v] });
52             }
53         }
54     }
55     cout << ans << endl;
56 }
57 
58 
59 int main()
60 {
61     int a, b, c;
62     cin >> n >> m;
63     for (int i = 1; i <= m; ++i) {
64         cin >> a >> b >> c;
65         G[a].push_back({ b, c });
66         G[b].push_back({ a, c });
67     }
68     Prim({ 1, 0 });
69     //system("pause");
70     return 0;
71 }

 

posted @ 2015-02-13 00:16  UsedRose  阅读(154)  评论(0编辑  收藏  举报