kruskal算法相比prim算法思路简单,不用处理边界问题,不用堆优化,所以一般稀疏图都用Kruskal。
Kruskal算法时间复杂度O(mlogm)
每条边存结构体里,排序需要在结构体里重载小于号
判断a,b点是否连通以及将点假如集合中需要并查集的知识
- #include
- #include
- #include
-
- using namespace std;
-
- const int N = 100010, M = 200010;
-
- int n, m;
- int p[N];
-
- struct Edge
- {
- int a, b, w;
- bool operator< (const Edge& W)const
- {
- return w < W.w;
- }
- }edges[M];
-
- int find(int x)
- {
- if(p[x] != x) p[x] = find(p[x]);
- return p[x];
- }
-
- int Kruskal()
- {
- int res = 0,cnt = 0;
- for(int i = 1; i <= n; i ++ )
- {
- p[i] = i;
- }
- for(int i = 0; i < m; i ++ )
- {
- int a = find(edges[i].a), b = find(edges[i].b);
- if(a != b)
- {
- p[a] = b;
- res += edges[i].w;
- cnt ++ ;
- }
- }
- if(cnt < n - 1) return 0;
- else return res;
- }
-
- int main()
- {
- cin >> n >> m;
- for(int i = 0; i < m; i ++ )
- {
- int a, b, w;
- cin >> a >> b >> w;
- edges[i].a = a, edges[i].b = b, edges[i].w = w;
- }
- sort(edges, edges + m);
- int t = Kruskal();
- if(!t) cout << "impossible" << endl;
- else cout << t << endl;
- return 0;
- }