很简单的最小生成树,只要把已经有了的边的cost设为0就可以了
#include<iostream> #include<cstdio> #include<vector> #include<algorithm> using namespace std; const int MAX=1000000; struct node { int left,right,cost; }road[MAX]; bool cmp(node x,node y){return x.cost<y.cost;} int p[MAX],m,n; int find(int x){return x==p[x]? x:p[x]=find(p[x]);} int kruskal() { int ans=0; for (int i=0;i<=n;i++) p[i]=i; for (int i=0;i<m;i++) { int x=find(road[i].left); int y=find(road[i].right); if(x!=y) { ans+=road[i].cost; p[x]=y; } } return ans; } int main() { int x,y,c,G[101][101],q; while(scanf("%d",&n)!=EOF) { for (int i=1;i<=n;i++) for (int j=1;j<=n;j++) scanf("%d",&G[i][j]); scanf("%d",&q); for (int i=0;i<q;i++) { scanf("%d%d",&x,&y); G[x][y]=0; } m=0; for (int i=1;i<=n;i++) for (int j=1;j<=n;j++) { if (i!=j) { road[m].left=i; road[m].right=j; road[m].cost=G[i][j]; m++; } } sort(road,road+m,cmp); printf("%d\n",kruskal()); } return 0; }
hust 1102 Constructing Roads,布布扣,bubuko.com
原文:http://www.cnblogs.com/chensunrise/p/3719790.html