[On] [FIG minimum spanning] USACO 3.1 Agri-Net network the shortest (minimum spanning tree)

Description

Farmer John was elected mayor of their town! One of his campaign promises was in town to establish the Internet and connect to all farms. Of course, he needs your help. John has given his farm and arranged for a high-speed network lines, he wanted to share this line to other farms. In order to use the smallest consumer, he wanted to lay the shortest optical fiber to connect all the farms. You will get a list of connection costs between each farm, you must be able to connect all the farms and find the shortest program with optical fiber. The distance between each of the two farms will not be more than 100,000

Input

The first line: the number of farms, N (3 <= N < = 100).
The second end of line ...: subsequent lines contain a N * N matrix representing the distance between each farm. In theory, they are N lines, each consisting of N space-separated number composed, in fact, they are limited to 80 characters, so some guilds followed by other lines. Of course, the diagonal will be 0, since the distance from the i-th to the farm itself.

Output

Only one output, which is connected to an optical fiber comprising a minimum length of each farm.

Sample Input

4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0

Sample Output

28


Problem-solving ideas

Topic: give you an undirected graph, minimum spanning tree
Input: an undirected graph
process: minimum spanning tree
output: tree edges and
(So much, in fact, I want to express this problem is a minimum spanning tree template)
cheerful recommendation prim algorithm and kruskal algorithm (you do not want to see, I do not want to explain)


The prim notes copied over

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int INF=0x7fffffff;
int v[200],n,a[200][200],Gun,dis[200];
void prim(){
	memset(dis,0x7f,sizeof(dis));//无穷大
	dis[1]=0;//固定起点1
	for(int i=1;i<=n;i++){
		int ins=INF,k;
		for(int j=1;j<=n;j++)
		    if(dis[j]<ins&&!v[j])//找蓝点最小
		    	ins=dis[j],k=j;
		v[k]=1;//变白点
		Gun+=dis[k];//累计答案
		for(int j=1;j<=n;j++)
		    if((a[k][j]<dis[j])&&!v[j]&&a[k][j])//更新每个蓝点连接最小生成树的边
		        dis[j]=a[k][j];
	}
}
int main(){
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
		for(int j=1;j<=n;j++)
			scanf("%d",&a[i][j]);
	prim();
	printf("%d",Gun);
}

发布了45 篇原创文章 · 获赞 0 · 访问量 356

Guess you like

Origin blog.csdn.net/qq_39940018/article/details/103641396
Recommended