最小生成树水题,写一个试试ubuntu下的nsight好用否!
将已经建好的路的权值赋为0就OK,然后用prim算法构建最小生成树。
#include <stdio.h> #include <string.h> #define N 101 #define INF 0x3fffffff int first[N],visited[N],dis[N],top,n; struct edge{ int y,w,next; }e[N*N]; void add(int x,int y,int w){ e[top].y = y; e[top].w = w; e[top].next = first[x]; first[x] = top++; } void update(int x,int y){ int i; for(i = first[x];i!=-1;i=e[i].next) if(e[i].y == y){ e[i].w = 0; return; } } void init(){ int i; memset(first,-1,sizeof(first)); memset(visited,0,sizeof(visited)); top = 0; for(i = 0;i<=n;i++) dis[i] = INF; } int prim(){ int i,j,pos,min,res = 0; for(i = first[1];i!=-1;i=e[i].next) dis[e[i].y] = e[i].w; pos = 1; visited[1] = 1; for(i = 1;i<n;i++){ min = INF; for(j = 1;j<=n;j++) if(!visited[j] && dis[j]<min){ pos = j; min = dis[j]; } visited[pos] = 1; res += min; for(j = first[pos];j!=-1;j=e[j].next) if(!visited[e[j].y] && dis[e[j].y]>e[j].w) dis[e[j].y] = e[j].w; } return res; } int main(){ //freopen("a.txt","r",stdin); while(scanf("%d",&n)!=EOF){ int i,j,w,num; init(); for(i = 1;i<=n;i++) for(j = 1;j<=n;j++){ scanf("%d",&w); if(i!=j) add(i,j,w); } scanf("%d",&num); while(num--){ scanf("%d %d",&i,&j); update(i,j);update(j,i); } printf("%d\n",prim()); } return 0; }