Online Judge | Problem Set | Authors | Online Contests | User | ||||||
---|---|---|---|---|---|---|---|---|---|---|
Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest |
贴一下两种prim求该题的最大生成树一种是将边权变为负,另一种直接将求最小的反一下,求最大和最小道理一样的。可能用邻接表可能更快一些,kruskal写起来太麻烦一直不想用。 1. #include <stdio.h> #include <limits.h> #define MAXN 1001 int G[MAXN][MAXN],vexnum; int dis[MAXN],visited[MAXN]; void Initial(int N) { int i,j; for(i=1;i<=N;++i) for(j=1;j<=i;++j) G[i][j]=G[j][i]=INT_MAX; vexnum=N; } int FindMin() { int i,k=-1,min=INT_MAX; for(i=1;i<=vexnum;++i) { if(visited[i]==1) continue; if(dis[i]<min) min=dis[i],k=i; } return k; } int Prim(int k) { int i,j,lowcost=0; for(i=1;i<=vexnum;++i) dis[i]=G[k][i],visited[i]=0; dis[k]=0,visited[k]=1; for(i=1;i<vexnum;++i) { if((k=FindMin())==-1) return 1; visited[k]=1,lowcost+=dis[k]; for(j=1;j<=vexnum;++j) { if(visited[j]==1||G[k][j]==INT_MAX) continue; if(dis[j]>G[k][j]) dis[j]=G[k][j]; } } return lowcost; } int main() { int N,M; int a,b,c; while(scanf("%d %d",&N,&M)!=EOF) { Initial(N); while(M--) { scanf("%d %d %d",&a,&b,&c); if(G[a][b]>-c) G[a][b]=G[b][a]=-c; } printf("%d\n",-Prim(1)); } return 0; } 2. #include <stdio.h> #include <limits.h> #define MAXN 1001 int G[MAXN][MAXN],vexnum; int dis[MAXN],visited[MAXN]; void Initial(int N) { int i,j; for(i=1;i<=N;++i) for(j=1;j<=i;++j) G[i][j]=G[j][i]=INT_MIN; vexnum=N; } int FindMax() { int i,k=-1,max=INT_MIN; for(i=1;i<=vexnum;++i) { if(visited[i]==1) continue; if(dis[i]>max) max=dis[i],k=i; } return k; } int Prim(int k) { int i,j,lowcost=0; for(i=1;i<=vexnum;++i) dis[i]=G[k][i],visited[i]=0; dis[k]=0,visited[k]=1; for(i=1;i<vexnum;++i) { if((k=FindMax())==-1) return -1; visited[k]=1,lowcost+=dis[k]; for(j=1;j<=vexnum;++j) { if(visited[j]==1||G[k][j]==INT_MAX) continue; if(dis[j]<G[k][j]) dis[j]=G[k][j]; } } return lowcost; } int main() { int N,M; int a,b,c,k; while(scanf("%d %d",&N,&M)!=EOF) { Initial(N); while(M--) { scanf("%d %d %d",&a,&b,&c); if(G[a][b]<c) G[a][b]=G[b][a]=c; } if((k=Prim(1))==-1) printf("-1\n"); else printf("%d\n",k); } return 0; } Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator