标签:
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 38513 Accepted Submission(s): 17424
1 #include <cstdio> 2 #include <algorithm> 3 using namespace std; 4 5 int N, M; 6 struct Edge{ 7 int u, v, w; 8 bool operator() (Edge a, Edge b) 9 { 10 return a.w<b.w; 11 } 12 }; 13 Edge e[5055]; 14 int f[105]; 15 16 int getf(int x) 17 { 18 return x == f[x] ? f[x] : f[x] = getf(f[x]); 19 } 20 21 bool merge(int a, int b) 22 { 23 int t1 = getf(a); 24 int t2 = getf(b); 25 if(t1 != t2){ 26 f[t2] = t1; 27 return true; 28 } 29 return false; 30 } 31 32 void kruskal() 33 { 34 for(int i = 1; i <= N; ++i) 35 f[i] = i; 36 sort(e+1, e+1+M, Edge()); //按边的权值从小到大排序 37 int ans = 0; 38 int cnt = 0; //记录生成树的边数 39 for(int i = 1; i <= M; ++i){ 40 if(merge(e[i].u, e[i].v)){ //用并查集判断两个结点是否在同一个集合中 41 ans += e[i].w; 42 ++cnt; 43 } 44 if(cnt == N-1) //直到选用了N-1条边后退出循环 45 break; 46 } 47 printf("%d\n", ans); 48 } 49 50 int main() 51 { 52 while(scanf("%d", &N), N){ 53 M = N*(N-1)/2; 54 for(int i = 1; i <= M; ++i){ 55 scanf("%d%d%d", &e[i].u, &e[i].v, &e[i].w); 56 } 57 kruskal(); 58 } 59 return 0; 60 }
Prim
1 #include <cstdio> 2 #include <cstring> 3 4 const int INF = 0x3f3f3f3f; 5 int N, M; 6 int e[105][105]; 7 int dis[105]; //记录非树结点到生成树的最小距离 8 bool vis[105]; 9 10 void prim() 11 { 12 memset(vis, 0, sizeof(vis)); 13 for(int i = 1; i <= N; ++i) 14 for(int j = 1; j <= N; ++j) 15 e[i][j] = (i == j ? 0 : INF); 16 int m = N*(N-1)/2; 17 int u, v, w; 18 for(int i = 1; i <= m; ++i){ 19 scanf("%d%d%d", &u, &v, &w); 20 e[u][v] = e[v][u] = w; //注意是无向图 21 } 22 for(int i = 1; i <= N; ++i) 23 dis[i] = e[1][i]; 24 vis[1] = true; 25 int ans = 0; 26 int cnt = 1; //记录生成树的结点数 27 while(cnt<N){ 28 int min_dis = INF, u; 29 for(int i = 1; i <= N; ++i){ 30 if(!vis[i] && dis[i]<min_dis){ 31 min_dis = dis[u = i]; 32 } 33 } 34 vis[u] = true; 35 ++cnt; 36 ans += dis[u]; 37 //更新非树结点到生成树的最小距离 38 for(int i = 1; i <= N; ++i){ 39 if(!vis[i] && e[u][i]<dis[i]){ 40 dis[i] = e[u][i]; 41 } 42 } 43 } 44 printf("%d\n", ans); 45 } 46 47 int main() 48 { 49 while(scanf("%d", &N), N){ 50 prim(); 51 } 52 return 0; 53 }
标签:
原文地址:http://www.cnblogs.com/inmoonlight/p/5647074.html