Graph theory [] [] optimal wiring minimum spanning tree problem

Description

N school computer, in order to facilitate data transmission, now want to connect them with the data line. It refers to two computers are connected with a cable connection between them. Due to the different positions in which the computer, and therefore the cost of different connection of two computers are often different.
Of course, if any of the two computers are connected to the data lines, the cost will be quite huge. In order to save costs, we used indirect means of transmission of data, i.e., a computer can indirectly by several computers (as transfer) to achieve connection with another computer.
Now you are responsible for connecting these computers, your task is to make any two computers are communicating (whether direct or indirect).

Input

Input file wire.in, a first behavior integer n (2 <= n <= 100), represents the number of computers. After the n lines of n integers. X + 1 The first column in row y represents an integer of direct computer connection charges and the x-y stage computer.

Output

Output file wire.out, an integer that represents the minimum connection fee.

Sample Input

3
0 1 2
1 0 1
2 1 0

Sample Output

2 (Note: 1 and 2,2 indicates that the connection 3 and a cost of 2)


Problem-solving ideas

Obviously the minimum spanning tree template

kruskal algorithm
each time to find the smallest edge, if not a collection of two points connected by an edge, then put two points together even
Here Insert Picture Description
constantly looking for the shortest edge, and this edge is not a collection of two points in
Here Insert Picture Description
the final
Here Insert Picture Description
the way push prim algorithm


#include<iostream>
#include<cstdio>
using namespace std;
const int INF=0x7fffffff;
int a[200][200],n,p[200],Gun;
void kruskal(){
	for(int g=1;g<n;g++){//因为必定只会连n-1条边
		int mi=INF,k,l;
		for(int i=1;i<=n;i++)
		    for(int j=1;j<=n;j++)
		        if(a[i][j]<mi&&a[i][j]&&p[i]!=p[j]){//两点不在一个集合p[i]!=p[j]
		        	mi=a[i][j];
		        	k=i,l=j;
		        }
	    Gun+=a[k][l]; //累计答案
	    int s=p[k];
		for(int i=1;i<=n;i++)
		    if(p[i]==s)//因为总有一个i==k,把p[k]赋成p[l],后面都赋值不了了
		       p[i]=p[l];
	}
}
int main(){
	scanf("%d",&n);
	for(int i=1;i<=n;i++){
		p[i]=i;
		for(int j=1;j<=n;j++)
		    scanf("%d",&a[i][j]);
	}
	kruskal();
	printf("%d",Gun);
}
Published 45 original articles · won praise 0 · Views 357

Guess you like

Origin blog.csdn.net/qq_39940018/article/details/103641177