HDU1102

来源:互联网 发布:json.encode 编辑:程序博客网 时间:2024/05/17 06:19

题目:

Constructing Roads
Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 4585    Accepted Submission(s): 1617


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.

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
 

Source
kicc
 

Recommend
Eddy

翻译:

问题描述:

有N个村庄,标记为1-N,你现在要去建一些街道,使每两个村庄之间都能够连通,如果两个村庄A、B之间有一条街道,或者有一个村庄C,C与A和C与B之间都有街道相连,我们就说A和B是连通的,现在已知一些村庄之间的街道是已经修好的,你的任务是建设其他的街道,目的是让所有的村庄都是连通的,并且街道总长度最小。

输入:

第一行有一个整数N(3<=N<=100),N是村庄的数量,然后是N行,第 i 行包含N个整数,这N个整数的第 j 个是第 i 个村庄到第 j 个村庄的距离,这个距离在1到1000,包括端点,然后是一个整数Q,(0<=Q<=N*(N+1)/2),接着是Q行,每一行有两个整数a,b(1<=a<b<=N),表示a村到b村之间的街道已经修好。

输出:

输出一行,含有一个整数,表示所有需要修的街道的最小长度。

 

该题最大的问题就是没有说明要有多组测试数据,我第一次也以为只有一组测试数据,结果果断WA,其实只是一道基本的最小生成树,只要把已经修好的街道的距离置为 0 ,然后调用最小生成树的算法,就能得到正确结果。

 

这是我写的源码,使用了邻接矩阵表示图的最小生成树prim算法模板:

#include<iostream>
using namespace std;
int main()
{
 int prim(int cost[][200],int n);
 int n,q;
 int i,j;
 int x,y;
 int a[200][200];
 while(cin>>n)
 { for(i=0;i<n;i++)
  for(j=0;j<n;j++)
   a[i][j]=100000;
 for(i=0;i<n;i++)
 {
  for(j=0;j<n;j++)
  {
   cin>>a[i][j];
  }
 }
 cin>>q;
 for(i=0;i<q;i++)
 {
  cin>>x>>y;
  a[x-1][y-1]=a[y-1][x-1]=0;
 }
 cout<<prim(a,n)<<endl;
 }
 return 0;
}
int prim(int cost[][200],int n)
{
 int low[10000],vis[10000]={0};
 int i,j,p;
 int min,res=0;
 vis[0]=1;
 for(i=1;i<n;i++)low[i]=cost[0][i];
 for(i=1;i<n;i++)
 {
  min=100000;p=-1;
  for(j=0;j<n;j++)
  {
   if(0==vis[j]&&min>low[j])
   {
    min=low[j];
    p=j;
   }
  }
   if(min==100000)return -1;
   res+=min;vis[p]=1;
   for(j=0;j<n;j++)
    if(0==vis[j]&&low[j]>cost[p][j])
     low[j]=cost[p][j];
 }
 return res;
}

原创粉丝点击