标签:
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 44147 | Accepted: 18054 |
Description
Input
Output
Sample Input
4 0 4 9 21 4 0 8 17 9 8 0 16 21 17 16 0
Sample Output
28
Source
prime做法:
1 #include <cstdio> 2 #include <cstring> 3 #include <string> 4 #include <queue> 5 #include <stack> 6 #include <iostream> 7 using namespace std; 8 #define lengthmax 100005 9 int map[105][105]; 10 int dis[105]; 11 int main(){ 12 //freopen("D:\\INPUT.txt","r",stdin); 13 int n; 14 while(scanf("%d",&n)!=EOF){ 15 int i,j; 16 for(i=0;i<n;i++){ 17 dis[i]=lengthmax; 18 for(j=0;j<n;j++){ 19 scanf("%d",&map[i][j]); 20 } 21 } 22 int m=1,mink,s=0,min,sum=0; 23 dis[0]=0;//已经在集合里面 24 while(m<n){//循环n-1次 25 min=lengthmax; 26 for(i=1;i<n;i++){ 27 if(dis[i]>map[s][i]){//更新 28 dis[i]=map[s][i]; 29 } 30 if(dis[i]&&min>dis[i]){ 31 min=dis[i]; 32 mink=i; 33 } 34 } 35 //cout<<mink<<endl; 36 //cout<<min<<endl; 37 sum+=min; 38 dis[mink]=0; 39 s=mink; 40 m++; 41 } 42 cout<<sum<<endl; 43 } 44 return 0; 45 }
kruskal做法:
1 #include <cstdio> 2 #include <cstring> 3 #include <string> 4 #include <queue> 5 #include <stack> 6 #include <algorithm> 7 #include <iostream> 8 using namespace std; 9 struct node{ 10 int u,v,l; 11 }; 12 node p[5000]; 13 int fa[105]; 14 bool cmp(node a,node b){ 15 return a.l<b.l; 16 } 17 int findfa(int a){ 18 if(a!=fa[a]){ 19 fa[a]=findfa(fa[a]);//attention! 20 } 21 return fa[a]; 22 } 23 int main(){ 24 //freopen("D:\\INPUT.txt","r",stdin); 25 int n; 26 while(scanf("%d",&n)!=EOF){ 27 int i,j,k; 28 for(i=0;i<n;i++){ 29 fa[i]=i; 30 } 31 int num; 32 k=0; 33 for(i=0;i<n;i++){ 34 for(j=0;j<n;j++){ 35 scanf("%d",&num); 36 if(i<j){ 37 p[k].u=i; 38 p[k].v=j; 39 p[k++].l=num; 40 } 41 } 42 } 43 int sum=0; 44 num=1; 45 sort(p,p+k,cmp); 46 47 for(i=0;i<k;i++){ 48 if(num==n){ 49 break; 50 } 51 int u=findfa(p[i].u); 52 int v=findfa(p[i].v); 53 if(u==v){ 54 continue; 55 } 56 if(u>v){ 57 fa[v]=u; 58 } 59 else{ 60 fa[u]=v; 61 } 62 sum+=p[i].l; 63 num++; 64 } 65 cout<<sum<<endl; 66 } 67 return 0; 68 }
标签:
原文地址:http://www.cnblogs.com/Deribs4/p/4645114.html