Minimum spanning tree ------------- shortest network

Farmer John was chosen as the mayor of their town!
One of his campaign promises was to establish the Internet in the town and connect to all the farms.
John has arranged a high-speed network line for his farm, and he wants to share this line with other farms.
The number of John's farm is 1, and the number of other farms is 2∼n2∼n.
In order to minimize costs, he hopes that the total length of fiber used to connect all the farms should be as short as possible.
You will get a list of the connection distances between the farms. You must find a solution that can connect all the farms and minimize the fiber used.
Input format The
first line contains an integer nn, indicating the number of farms.
The next nn rows, each row contains nn integers, enter a symmetric matrix with all 0s on the diagonal.

The integer in the yy column of row x + 1x + 1 represents the length of fiber required to connect farm xx and farm yy.
Output format
Output an integer that represents the minimum required fiber length.
Data range
3≤n≤1003≤n≤100

The distance between every two farms is a non-negative integer and does not exceed 100,000.
Input example:
4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0

Sample output:
28

Pure prime algorithm

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 110;
int n;
int w[N][N];
int dist[N];
int st[N];
int prim(){
 int res = 0;
 memset(dist, 0x3f, sizeof dist);
 dist[1] = 0;
  for (int i = 0; i < n; i ++){
  int t = -1;
  for (int j = 1; j <= n; j ++)
     if (!st[j] && (t == -1 || dist[t] > dist[j]))
       t = j;
    res += dist[t];
  st[t] = true;
   for (int j = 1; j <= n; j ++)    dist[j] = min(dist[j], w[t][j]);
 }
  return res;
}
int main(){
 cin >> n;
 for (int i = 1; i <= n; i ++)
     for (int j = 1; j <= n; j ++)
        cin >> w[i][j];
         cout << prim() << endl;
  return 0;
} 
164 original articles published · Like 112 · Visitors 6782

Guess you like

Origin blog.csdn.net/qq_45772483/article/details/105377382