Prim板子

Prim:每次都选一个距离集合最小的点加入集合中,最终形成的就是最小生成树(与Dijkstra最大的区别,其余代码和Dijkstra没啥不同)

因为和Dijikstra思想差不多,所以也可以用堆优化,但是基本都不用,因为有更好的Kruskal

 1 #include <iostream>
 2 #include <string.h>
 3 using namespace std;
 4 
 5 const int N = 509,M = 100009;
 6 
 7 int g[N][N];
 8 int n,m,dist[N],st[N],res,cnt;
 9 
10 bool Prim()
11 {
12     memset(dist,0x3f,sizeof dist);
13     dist[1] = 0;
14     for(int i = 0;i < n;++i)
15     {
16         int t = -1;
17         for(int j = 1;j <= n;++j)
18             if(!st[j] && (t == -1 || dist[t] > dist[j]))
19                 t = j;
20         if(dist[t] == 0x3f3f3f3f)   //找不到下一个能加入集合的点,说明不连通
21             return false;
22         st[t] = 1;
23         res += dist[t];
24         for(int j = 1;j <= n;++j)
25             dist[j] = min(dist[j],g[t][j]);
26     }
27     return true;
28 }
29 
30 int main()
31 {
32     cin >> n >> m;
33     memset(g,0x3f,sizeof g);
34     while(m--)
35     {
36         int a,b,c;
37         cin >> a >> b >> c;
38         g[a][b] = g[b][a] = min(g[a][b],c);
39     }
40     if(Prim())
41         cout << res << endl;
42     else
43         cout << "impossible" << endl;
44     return 0;
45 }

 

posted @ 2021-10-22 10:15  Modest-Hamilton  阅读(46)  评论(0)    收藏  举报