Problem A

来源:互联网 发布:核算成本的软件 编辑:程序博客网 时间:2024/05/16 18:50
Problem 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. <br><br>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.<br>
 

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.<br><br>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.<br>
 

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. <br>
 

Sample Input
30 990 692990 0 179692 179 011 2
 

Sample Output

179

代码:

 #include<iostream> #include<algorithm>  using namespace std;  struct node{      int from;      int to;      int w;      };node  edge[102*100];  int parent[102];  bool cmp(node a,node b) {     if(a.w<=b.w) return true;     return false; }//查找已经建完道路的顶点int find(int a){    if(a!=parent[a])        return find(parent[a]);    else return a;} int kruskal(int n,int m) {     sort(edge,edge+m,cmp);//将边的权值从小到大排序     int i,x,y,ans=0;    for(i=0;i<m;i++)     {        x=edge[i].from;        y=edge[i].to;        x=find(x);        y=find(y);        if(x!=y)        {            ans+=edge[i].w;            parent[y]=x;        }}   return ans; } int main() {     int n,q,k,i,j,m;     while(cin>>n)     {         m=0;        for(i=1;i<=n;i++)         {             for(j=1;j<=n;j++)             {                 cin>>k;                if(i>=j) continue;//标记过的不用重复记录                 edge[m].from=i;                 edge[m].to=j;                 edge[m].w=k;            m++;           }        }        for(k=1;k<=n;k++)        parent[k]=k;         cin>>q;         //将建完的道路的起点和终点都置为相同的起点        for(k=1;k<=q;k++)        {            cin>>i>>j;           i=find(i);            j=find(j);             parent[j]=i;      }      //n个点,m条边        cout<<kruskal(n,m)<<endl;     }     return 0; }

0 0