http://blog.csdn.net/zck921031/article/details/7688820
http://blog.csdn.net/ffq5050139/article/details/7850220
就是一道最小生成树的题目,说xx到xx的路以修好,令其权值为0就可以了。
Description
There are N villages, which are numbered from 1 to N, and you should build some roads such that every two villages can connect to each other. We say two village A and B are connected, if and only if there is a road between A and B, or there exists a village C such that there is a road between A and C, and C and B are connected.
We know that there are already some roads between some villages and your job is the build some roads such that all the villages are connect and the length of all the roads built is minimum.
Input
The first line is an integer N (3 <= N <= 100), which is the number of villages. Then come N lines, the i-th of which contains N integers, and the j-th of these N integers is the distance (the distance should be an integer within [1, 1000]) between village i and village j.
Then there is an integer Q (0 <= Q <= N * (N + 1) / 2). Then come Q lines, each line contains two integers a and b (1 <= a < b <= N), which means the road between village a and village b has been built.
Output
You should output a line contains an integer, which is the length of all the roads to be built such that all the villages are connected, and this value is minimum.
Sample Input
3
0 990 692
990 0 179
692 179 0
1
1 2
Sample Output
179
变形的Kruscal算法:
如下:
using namespace std; const int V=101; int father[V],map[V][V]; struct point { int s,v,rank; }p[V*V];//边集合 int cmp(const void* a,const void* b) { point* t1=(point*)a; point* t2=(point*)b; return t1->rank>t2->rank; } int find(int x) { if(x!=father[x]) father[x]=find(father[x]); return father[x]; } void Union(int a,int b) { int x=find(a); int y=find(b); if(x==y) return; father[y]=x; } bool found(int n) { int x=find(0); for(int i=0;i<n;i++) if(find(i)!=x) return false; return true; } int kruskal(int map[][V],int n) { int i,j,cnt,mst=0; for(i=0,cnt=0;i<n;i++) { father[i]=i; for(j=0;j<n;j++) { p[cnt].s=i; p[cnt].v=j; p[cnt].rank=map[i][j]; cnt++; } } //qsort(p,p+n*n,cmp); qsort(p,n*n,sizeof(point),cmp); for(i=0;i<n*n;i++) { if(p[i].rank!=0&&p[i].rank!=-1) { if(find(p[i].s)!=find(p[i].v)) { mst+=p[i].rank; } Union(p[i].s,p[i].v); if(found(n)==true) return mst; } else if(p[i].rank==-1) { Union(p[i].s,p[i].v); if(found(n)==true) return mst; } } } int main() { int n; scanf("%d", &n); int m,i,j,p,q,cnt=0; memset(map,0,sizeof(map)); for(i=0;i<n;i++) for(j=0;j<n;j++) scanf("%d",&map[i][j]); cin>>m; while(m--) { cin>>p>>q; map[p-1][q-1]=-1; } cout<<kruskal(map,n)<<endl; }