最小生成树(模板题)

Networking
The island nation of Flatopia is perfectly flat. Unfortunately, Flatopia has a very poor system of public highways. The Flatopian government is aware of this problem and has already constructed a number of highways connecting some of the most important towns. However, there are still some towns that you can’t reach via a highway. It is necessary to build more highways so that it will be possible to drive between any pair of towns without leaving the highway system.

Flatopian towns are numbered from 1 to N and town i has a position given by the Cartesian coordinates (xi, yi). Each highway connects exaclty two towns. All highways (both the original ones and the ones that are to be built) follow straight lines, and thus their length is equal to Cartesian distance between towns. All highways can be used in both directions. Highways can freely cross each other, but a driver can only switch between highways at a town that is located at the end of both highways.

The Flatopian government wants to minimize the cost of building new highways. However, they want to guarantee that every town is highway-reachable from every other town. Since Flatopia is so flat, the cost of a highway is always proportional to its length. Thus, the least expensive highway system will be the one that minimizes the total highways length.
Input
The input consists of two parts. The first part describes all towns in the country, and the second part describes all of the highways that have already been built.

The first line of the input file contains a single integer N (1 <= N <= 750), representing the number of towns. The next N lines each contain two integers, xi and yi separated by a space. These values give the coordinates of ith town (for i from 1 to N). Coordinates will have an absolute value no greater than 10000. Every town has a unique location.

The next line contains a single integer M (0 <= M <= 1000), representing the number of existing highways. The next M lines each contain a pair of integers separated by a space. These two integers give a pair of town numbers which are already connected by a highway. Each pair of towns is connected by at most one highway.
Output
Write to the output a single line for each new highway that should be built in order to connect all towns with minimal possible total length of new highways. Each highway should be presented by printing town numbers that this highway connects, separated by a space.

If no new highways need to be built (all towns are already connected), then the output file should be created but it should be empty.
输入
1 0

2 3
1 2 37
2 1 17
1 2 68

3 7
1 2 19
2 3 11
3 1 7
1 3 5
2 3 89
3 1 91
1 2 32

5 7
1 2 5
2 3 7
2 4 8
4 5 11
3 5 10
1 5 6
4 2 12

0
输出
0
17
16
26

Kruskal算法
将每条电缆的长度从小到大排序,用并查集合并,找到经过每一个点最短的长度

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
#include <iostream>
using namespace std;
const int N =1e6;
int f[N], mx[N], siz[N];
char c[N];
struct node
{
  int x, y, t;
} s[N];
void init(int x)//初始化
{
  for (int i = 1; i <= x; i++)
  {
    f[i] = i;
    siz[i] = 1;
  }
}
int find(int x)
{
  if (f[x] == x)
    return x;
  return f[x] = find(f[x]);
}
bool cmp(node x,node y)
{
  return x.t<y.t;
}
int main()
{
  int n, m, nn, mm, t, i, j;
  char x, y;

  while (cin >> n)
  {
    if(n==0)
    break;
    cin>>m;
    init(N);
    int res = 0;
    for (i = 1; i <= m; i++)
    {
      int x,y,z;
      cin>>x>>y>>z;
        s[res].x = x;
        s[res].y =y;
        s[res++].t = z;
    }
    int sum = 0;
    sort(s,s+res,cmp);//权值从小到大排序
    for (i = 0; i < res; i++)
    {
      int a = find(s[i].x);
      int b = find(s[i].y);
      if (a != b)
      {
        f[a] = b;
        sum += s[i].t;
      }
    }
    cout<<sum<<endl;
  }
  return 0;
}

prim算法
将第一个点放入一个集合中,找到这个点周围最短的路,标记一下走过的路,到下一个点,把下个点放入集合,以此类推,找完所有点,最短电缆长度就出来了

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
#include <iostream>
using namespace std;
const int N = 200005;
int e[110][110], dis[N], st[N];
int main()
{
  int n, m;
  while (scanf("%d", &n) != EOF)
  {
    if (n == 0)
      break;
    scanf("%d", &m);
    memset(e, N, sizeof(e));
    memset(st, 0, sizeof(st));
    for (int i = 1; i <= m; i++)
    {
      int x, y, tt;
      scanf("%d%d%d", &x, &y, &tt);
      if (e[x][y] > tt)
        e[x][y] = e[y][x] = tt;//x到y和y到x的距离z
    }
    int ans = 0;
    memset(dis, 0x3f, sizeof(dis));
    for (int i = 0; i < n; i++)
    {
      int t = 0;
      if (!i)
        t = 1;
      else
      {
        for (int j = 1; j <= n; j++)
        {
          if (!st[j] && dis[t] > dis[j])
            t = j;
        }
      }
      if (i)
        ans += dis[t];
      st[t] = 1;//走过的标记一下
      for (int j = 1; j <= n; j++)
      {
        if (!st[j])
        {
          dis[j] = min(dis[j], e[t][j]);
        }
      }
    }
    cout << ans << endl;
  }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
最小生成树(Minimum Spanning Tree,简称MST)是一种在连通图中找到最小权重生成树的算法。下面是一个使用Prim算法实现最小生成树的Python模板: ```python import sys class Graph: def __init__(self, vertices): self.V = vertices self.graph = [[0 for _ in range(vertices)] for _ in range(vertices)] def printMST(self, parent): print("边\t权重") for i in range(1, self.V): print(f"{parent[i]} - {i}\t{self.graph[i][parent[i]]}") def minKey(self, key, mstSet): min_val = sys.maxsize min_index = -1 for v in range(self.V): if key[v] < min_val and not mstSet[v]: min_val = key[v] min_index = v return min_index def primMST(self): key = [sys.maxsize] * self.V parent = [None] * self.V key = 0 mstSet = [False] * self.V parent = -1 for _ in range(self.V): u = self.minKey(key, mstSet) mstSet[u] = True for v in range(self.V): if ( self.graph[u][v] > 0 and not mstSet[v] and key[v] > self.graph[u][v] ): key[v] = self.graph[u][v] parent[v] = u self.printMST(parent) # 使用示例 g = Graph(5) g.graph = [ [0, 2, 0, 6, 0], [2, 0, 3, 8, 5], [0, 3, 0, 0, 7], [6, 8, 0, 0, 9], [0, 5, 7, 9, 0], ] g.primMST() ``` 这个模板使用了Prim算法来实现最小生成树。首先,我们定义了一个Graph类,其中包含了图的顶点数和邻接矩阵。`primMST`方法是Prim算法的实现,它通过选择权重最小的边来构建最小生成树。`minKey`方法用于找到当前权重最小的顶点。`printMST`方法用于打印最小生成树的边和权重。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值