最小生成树就是一个连通图的最小连通子集。
Kruskual算法:
hdu1223 code:
#include <iostream> #include <cstdio> #include<set> #include<algorithm> #include<cstring> #include<cstdlib> #define maxn 105 typedef long long ll; using namespace std; typedef struct roads{ int s,e,dis; }Roads; int father[maxn]; int find(int x){ if(x!=father[x]) father[x]=find(father[x]); return father[x]; } bool compare(Roads a,Roads b){ return a.dis < b.dis; } Roads w[maxn*maxn]; int ans; bool vis[maxn]; int main() { int n; while(scanf("%d",&n)&&n!=0) { ans = 0; for(int i=0;i<=n;i++){ father[i]=i; } for(int i = 0;i < (n*(n-1))/2 ;i ++) { scanf("%d %d %d",&w[i].s,&w[i].e,&w[i].dis); } sort(w,w+(n*(n-1))/2,compare); memset(vis,0,sizeof(vis)); int cnt = 0; for(int i = 0;i < (n*(n-1))/2;i ++) { int x=find(w[i].s); int y=find(w[i].e); if(x!=y){ ans+=w[i].dis; father[x]=y; } } printf("%d ",ans); } return 0; }
prim算法:
hdu1102code:
#include <iostream> #include <algorithm> #include<queue> #include<cstdio> #include<cstring> #include<list> #define maxn 103 using namespace std; typedef long long ll; int dis[maxn]; int n; vector<int> q; int roads[maxn][maxn]; ll ans; void prime(){ for(int i = 1;i <= n;i ++) { q.push_back(i); dis[i] = roads[1][i]; } while(q.size()) { int t = 0; for(int i = 0;i < q.size();i ++){ if(dis[q[t]] > dis[q[i]]) { t = i; } } ans += dis[q[t]]; for(int i = 0;i < q.size();i ++) { if(roads[q[t]][q[i]] < dis[q[i]]){ dis[q[i]] = roads[q[t]][q[i]]; } } int temp = q[t]; q[t] = q[q.size() - 1]; q[q.size()-1] = temp; q.pop_back(); } } int main() { int m,a,b,q1; while(scanf("%d",&n)!=EOF){ q.clear(); ans = 0; for(int i = 1;i <= n;i ++){ for(int j = 1;j <= n;j ++){ scanf("%d",&roads[i][j]); } } cin >> m; for(int i = 1;i <= m;i ++){ scanf("%d %d",&a,&b); roads[a][b] = roads[b][a] = 0; } prime(); printf("%d ",ans); } return 0; }