Problem A
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 2 Accepted Submission(s) : 2
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
3 0 990 692 990 0 179 692 179 0 1 1 2
Sample Output
179
k算法 的意思 就是 先以一个位开始点 找到 与他链接最小的 然后 两个点 为中心 找到与这两个点区间 中最小的 以此类推 一直到找完
#include<stdio.h> #include<iostream> #include<string.h> using namespace std; int visit[1002]; int maa[105][105]; int main() { int t; int x,y; int f; int n; int i,j; while(cin>>t) { memset(visit,0,sizeof(visit)); for(i=1;i<=t;i++) { for(j=1;j<=t;j++) { scanf("%d",&f); maa[i][j]=f; } } cin>>n; for(i=1;i<=n;i++) { scanf("%d",&x); scanf("%d",&y); maa[x][y]=0; maa[y][x]=0; } int min1; int k; int sum=0; for(i=2;i<=t;i++) { min1=100000; for(j=2;j<=t;j++) { if(visit[j]==0&&min1>maa[1][j]) { min1=maa[1][j]; k=j; } } sum+=min1; visit[k]=1; for(j=2;j<=t;j++) { if(visit[j]==0&&maa[k][j]<maa[1][j]) maa[1][j]=maa[k][j]; } } cout<<sum<<endl; } return 0; }