kuangbin带你飞 最小生成树专题

A - Jungle Road

在这里插入图片描述
Input

The input consists of one to 100 data sets, followed by a final line containing only 0. Each data set starts with a line containing only a number n, which is the number of villages, 1 < n < 27, and the villages are labeled with the first n letters of the alphabet, capitalized. Each data set is completed with n-1 lines that start with village labels in alphabetical order. There is no line for the last village. Each line for a village starts with the village label followed by a number, k, of roads from this village to villages with labels later in the alphabet. If k is greater than 0, the line continues with data for each of the k roads. The data for each road is the village label for the other end of the road followed by the monthly maintenance cost in aacms for the road. Maintenance costs will be positive integers less than 100. All data fields in the row are separated by single blanks. The road network will always allow travel between all the villages. The network will never have more than 75 roads. No village will have more than 15 roads going to other villages (before or after in the alphabet). In the sample input below, the first data set goes with the map above.

Output

The output is one integer per line for each data set: the minimum cost in aacms per month to maintain a road system that connect all the villages. Caution: A brute force solution that examines every possible set of roads will not finish within the one minute time limit.

Sample Input

9
A 2 B 12 I 25
B 3 C 10 H 40 I 8
C 2 D 18 G 55
D 1 E 44
E 2 F 60 G 38
F 0
G 1 H 35
H 1 I 35
3
A 2 B 10 C 40
B 1 C 20
0

Sample Output

216
30

注意模板是需要村庄数和道路数的,题目中的输入只给出了村庄数,而道路数需要自己把每次输入的道路数相加求得总的道路数。

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <cstdio>
using namespace std;
const int N = 2e5;
typedef pair<int, int> P;
int bcj[5005];
int n, m, cnt, ans;
struct node {
    int u, v, w;
    inline bool operator < (const node &x) const {
        return w < x.w;
    }
} edge[200005];

int Find(int x)
{
    if(bcj[x] < 0) return x;
    return bcj[x] = Find(bcj[x]);
}

void kruskal()
{
    cnt = ans = 0;
    sort(edge, edge + m);
    for(int i = 0; i < m; ++i) {
        int u = Find(edge[i].u), v = Find(edge[i].v);
        if(u == v) continue;
        ans += edge[i].w;
        bcj[v] = u;
        cnt++;
        if(cnt == n - 1) break;   
    }
}

int main()
{
	char c,t;
	int x,num;
	while(scanf("%d",&n)!=EOF&&n)
    {
    	m=0;
    	for(int j=0;j<n-1;j++)
	    {
	    	cin>>c>>num;
		    for(int i = m; i < m+num; ++i) 
			{
				cin>>t>>x;
		        edge[i].u=c-'A';edge[i].v=t-'A';edge[i].w=x;
		    }
		    m+=num;
		}
		memset(bcj, -1, sizeof bcj);
	    kruskal();
	    printf("%d\n", ans);
	}
    return 0;
}

B - Networking

You are assigned to design network connections between certain points in a wide area. You are given a set of points in the area, and a set of possible routes for the cables that may connect pairs of points. For each possible route between two points, you are given the length of the cable that is needed to connect the points over that route. Note that there may exist many possible routes between two given points. It is assumed that the given possible routes connect (directly or indirectly) each two points in the area.
Your task is to design the network for the area, so that there is a connection (direct or indirect) between every two points (i.e., all the points are interconnected, but not necessarily by a direct cable), and that the total length of the used cable is minimal.

Input

The input file consists of a number of data sets. Each data set defines one required network. The first line of the set contains two integers: the first defines the number P of the given points, and the second the number R of given routes between the points. The following R lines define the given routes between the points, each giving three integer numbers: the first two numbers identify the points, and the third gives the length of the route. The numbers are separated with white spaces. A data set giving only one number P=0 denotes the end of the input. The data sets are separated with an empty line.
The maximal number of points is 50. The maximal length of a given route is 100. The number of possible routes is unlimited. The nodes are identified with integers between 1 and P (inclusive). The routes between two points i and j may be given as i j or as j i.
Output
For each data set, print one number on a separate line that gives the total length of the cable used for the entire designed network.

Sample Input

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

Sample Output

0
17
16
26

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <cstdio>
using namespace std;
const int N = 2e5 + 5;

int bcj[5005];
int n, m, cnt, ans;

struct node {
    int u, v, w;
    inline bool operator < (const node &x) const {
        return w < x.w;
    }
} edge[N];

int Find(int x)
{
    if (bcj[x] < 0) return x;
    return bcj[x] = Find(bcj[x]);
}

void kruskal()
{
	// cnt 记录的是边数
    cnt = ans = 0;
    // 从小到大排序 
    sort(edge, edge + m);
    for (int i = 0; i < m; i++) {
        int u = Find(edge[i].u), v = Find(edge[i].v);
        // 两点连通 
        if (u == v) 
			continue;
        ans += edge[i].w;
        bcj[v] = u;
        cnt++;
        // 生成了最小生成树 
        if (cnt == n - 1) 
			break;
    }
}

int main(void)
{
    while (scanf("%d", &n) != EOF && n) {
    	scanf("%d", &m);
	    memset(bcj, -1, sizeof bcj);
	    for (int i = 0; i < m; i++) {
	        scanf("%d %d %d", &edge[i].u, &edge[i].v, &edge[i].w);
	    }
	    kruskal();
	    printf("%d\n", ans);
	}
    
    return 0;
}

C - Building a Space Station

You are a member of the space station engineering team, and are assigned a task in the construction process of the station. You are expected to write a computer program to complete the task.
The space station is made up with a number of units, called cells. All cells are sphere-shaped, but their sizes are not necessarily uniform. Each cell is fixed at its predetermined position shortly after the station is successfully put into its orbit. It is quite strange that two cells may be touching each other, or even may be overlapping. In an extreme case, a cell may be totally enclosing another one. I do not know how such arrangements are possible.

All the cells must be connected, since crew members should be able to walk from any cell to any other cell. They can walk from a cell A to another cell B, if, (1) A and B are touching each other or overlapping, (2) A and B are connected by a `corridor’, or (3) there is a cell C such that walking from A to C, and also from B to C are both possible. Note that the condition (3) should be interpreted transitively.

You are expected to design a configuration, namely, which pairs of cells are to be connected with corridors. There is some freedom in the corridor configuration. For example, if there are three cells A, B and C, not touching nor overlapping each other, at least three plans are possible in order to connect all three cells. The first is to build corridors A-B and A-C, the second B-C and B-A, the third C-A and C-B. The cost of building a corridor is proportional to its length. Therefore, you should choose a plan with the shortest total length of the corridors.

You can ignore the width of a corridor. A corridor is built between points on two cells’ surfaces. It can be made arbitrarily long, but of course the shortest one is chosen. Even if two corridors A-B and C-D intersect in space, they are not considered to form a connection path between (for example) A and C. In other words, you may consider that two corridors never intersect.

Input

The input consists of multiple data sets. Each data set is given in the following format.

n
x1 y1 z1 r1
x2 y2 z2 r2

xn yn zn rn

The first line of a data set contains an integer n, which is the number of cells. n is positive, and does not exceed 100.

The following n lines are descriptions of cells. Four values in a line are x-, y- and z-coordinates of the center, and radius (called r in the rest of the problem) of the sphere, in this order. Each value is given by a decimal fraction, with 3 digits after the decimal point. Values are separated by a space character.

Each of x, y, z and r is positive and is less than 100.0.

The end of the input is indicated by a line containing a zero.

Output

For each data set, the shortest total length of the corridors should be printed, each in a separate line. The printed values should have 3 digits after the decimal point. They may not have an error greater than 0.001.

Note that if no corridors are necessary, that is, if all the cells are connected without corridors, the shortest total length of the corridors is 0.000.

Sample Input

3
10.000 10.000 50.000 10.000
40.000 10.000 50.000 10.000
40.000 40.000 50.000 10.000
2
30.000 30.000 30.000 20.000
40.000 40.000 40.000 20.000
5
5.729 15.143 3.996 25.837
6.013 14.372 4.818 10.671
80.115 63.292 84.477 15.120
64.095 80.924 70.029 14.881
39.472 85.116 71.369 5.553
0

Sample Output

20.000
0.000
73.834

给定n个点的坐标(xi, yi, zi)和点的半径,如果两个点的距离小于等于0,说明不用建立通道

否则需要建立通道,求出最小生成树的长度

当两个点的距离小于等于0时:

做法1、可以建立一条长度为0的边

做法2、也可以用Union操作进行合并

做法1:

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <cstdio>
using namespace std;
const int N = 2e5 + 5;

int bcj[5005];
int n, m, cnt;
double ans;
double x[105], y[105], z[105], r[105];

struct node {
    int u, v;
	double w;
    inline bool operator < (const node &x) const {
        return w < x.w;
    }
} edge[N];

int Find(int x)
{
    if (bcj[x] < 0) return x;
    return bcj[x] = Find(bcj[x]);
}

void kruskal()
{
	// cnt 记录的是边数
    cnt = ans = 0;
    // 从小到大排序 
    sort(edge, edge + m);
    for (int i = 0; i < m; i++) {
        int u = Find(edge[i].u), v = Find(edge[i].v);
        // 两点连通 
        if (u == v) 
			continue;
        ans += edge[i].w;
        bcj[v] = u;
        cnt++;
        // 生成了最小生成树 
        if (cnt == n - 1) 
			break;
    }
}

int main(void)
{
	while (scanf("%d", &n) != EOF && n) {
	    
	    memset(bcj, -1, sizeof bcj);
	    for (int i = 0; i < n; i++) {
	    	scanf("%lf%lf%lf%lf", &x[i], &y[i], &z[i], &r[i]);
	    }
	    m = 0;
	    double dis;
	    for (int i = 0; i < n; i++) {
	    	for (int j = i + 1; j < n; j++) {
	    		dis = sqrt(pow(x[i] - x[j], 2) + pow(y[i] - y[j], 2) + pow(z[i] - z[j], 2)) - r[i] - r[j];
	    		edge[m].u = i, edge[m].v = j;
				if (dis > 0) {
	    			edge[m++].w = dis;
	    		} else {
	    			edge[m++].w = 0;
	    		}
	    	}
	    }
	    kruskal();
	    printf("%.3f\n", ans);
	}
    
    return 0;
}

做法2:

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <cstdio>
using namespace std;
const int N = 2e5 + 5;

int bcj[5005];
int n, m, cnt;
double ans;
double x[105], y[105], z[105], r[105];

struct node {
    int u, v;
	double w;
    inline bool operator < (const node &x) const {
        return w < x.w;
    }
} edge[N];

int Find(int x)
{
    if (bcj[x] < 0) return x;
    return bcj[x] = Find(bcj[x]);
}

void Union(int x, int y)//合并两个集合
{
    x = Find(x), y = Find(y);//查找两集合的根节点
    if(x == y) return ;
    bcj[x] += bcj[y];//让x成为新集合的根节点
    bcj[y] = x;//让新集合的根节点成为y的根节点
}

void kruskal()
{
	// cnt 记录的是边数
    cnt = ans = 0;
    // 从小到大排序 
    sort(edge, edge + m);
    for (int i = 0; i < m; i++) {
        int u = Find(edge[i].u), v = Find(edge[i].v);
        // 两点连通 
        if (u == v) 
			continue;
        ans += edge[i].w;
        bcj[v] = u;
        cnt++;
        // 生成了最小生成树 
        if (cnt == n - 1) 
			break;
    }
}

int main(void)
{
	while (scanf("%d", &n) != EOF && n) {
	    
	    memset(bcj, -1, sizeof bcj);
	    for (int i = 0; i < n; i++) {
	    	scanf("%lf%lf%lf%lf", &x[i], &y[i], &z[i], &r[i]);
	    }
	    m = 0;
	    double dis;
	    for (int i = 0; i < n; i++) {
	    	for (int j = i + 1; j < n; j++) {
	    		dis = sqrt(pow(x[i] - x[j], 2) + pow(y[i] - y[j], 2) + pow(z[i] - z[j], 2)) - r[i] - r[j];
				if (dis > 0) {
					edge[m].u = i, edge[m].v = j;
	    			edge[m++].w = dis;
	    		} else {
	    			Union(i, j);
	    		}
	    	}
	    }
	    kruskal();
	    printf("%.3f\n", ans);
	}
    
    return 0;
}

D - Constructing Roads

链接:https://blog.csdn.net/weixin_43772166/article/details/98959120

E - QS Network

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <cstdio>
using namespace std;
const int N = 2e5 + 5;

int bcj[5005];
int n, m, cnt, ans;
int ma[1005][1005], cost[1005];

struct node {
    int u, v, w;
    inline bool operator < (const node &x) const {
        return w < x.w;
    }
} edge[N];

int Find(int x)
{
    if (bcj[x] < 0) return x;
    return bcj[x] = Find(bcj[x]);
}

void kruskal()
{
	// cnt 记录的是边数
    cnt = ans = 0;
    // 从小到大排序 
    sort(edge, edge + m);
    for (int i = 0; i < m; i++) {
        int u = Find(edge[i].u), v = Find(edge[i].v);
        // 两点连通 
        if (u == v) 
			continue;
        ans += edge[i].w;
        bcj[v] = u;
        cnt++;
        // 生成了最小生成树 
        if (cnt == n - 1) 
			break;
    }
}

int main(void)
{
	int t;
	cin >> t;
    while (t--) {
		scanf("%d", &n);
		for (int i = 0; i < n; i++) {
			cin >> cost[i];
		}
    	m = 0;
	    memset(bcj, -1, sizeof bcj);
	    for (int i = 0; i < n; i++) {
	    	for (int j = 0; j < n; j++) {
	    		cin >> ma[i][j];
	    	}
	    }
	    for (int i = 0; i < n; i++) {
	    	for (int j = i + 1; j < n; j++) {
	    		edge[m].u = i, edge[m].v = j, edge[m++].w = ma[i][j] + cost[i] + cost[j];
	    	}
	    }
	    kruskal();
	    printf("%d\n", ans);
	}
    
    return 0;
}

I - Agri-Net

Farmer John has been elected mayor of his town! One of his campaign promises was to bring internet connectivity to all farms in the area. He needs your help, of course.
Farmer John ordered a high speed connection for his farm and is going to share his connectivity with the other farmers. To minimize cost, he wants to lay the minimum amount of optical fiber to connect his farm to all the other farms.
Given a list of how much fiber it takes to connect each pair of farms, you must find the minimum amount of fiber needed to connect them all together. Each farm must connect to some other farm such that a packet can flow from any one farm to any other farm.
The distance between any two farms will not exceed 100,000.

Input

The input includes several cases. For each case, the first line contains the number of farms, N (3 <= N <= 100). The following lines contain the N x N conectivity matrix, where each element shows the distance from on farm to another. Logically, they are N lines of N space-separated integers. Physically, they are limited in length to 80 characters, so some lines continue onto others. Of course, the diagonal will be 0, since the distance from farm i to itself is not interesting for this problem.
Output
For each case, output a single integer length that is the sum of the minimum length of fiber required to connect the entire set of farms.

Sample Input

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

Sample Output

28

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <cstdio>
using namespace std;
const int N = 2e5 + 5;

int bcj[5005];
int n, m, cnt, ans;
int ma[105][105];

struct node {
    int u, v, w;
    inline bool operator < (const node &x) const {
        return w < x.w;
    }
} edge[N];

int Find(int x)
{
    if (bcj[x] < 0) return x;
    return bcj[x] = Find(bcj[x]);
}

void kruskal()
{
	// cnt 记录的是边数
    cnt = ans = 0;
    // 从小到大排序 
    sort(edge, edge + m);
    for (int i = 0; i < m; i++) {
        int u = Find(edge[i].u), v = Find(edge[i].v);
        // 两点连通 
        if (u == v) 
			continue;
        ans += edge[i].w;
        bcj[v] = u;
        cnt++;
        // 生成了最小生成树 
        if (cnt == n - 1) 
			break;
    }
}

int main(void)
{
    while (scanf("%d", &n) != EOF) {
    	m = 0;
	    memset(bcj, -1, sizeof bcj);
	    for (int i = 0; i < n; i++) {
	    	for (int j = 0; j < n; j++) {
	    		cin >> ma[i][j];
	    	}
	    }
	    for (int i = 0; i < n; i++) {
	    	for (int j = i + 1; j < n; j++) {
	    		edge[m].u = i, edge[m].v = j, edge[m++].w = ma[i][j];
	    	}
	    }
	    
	    kruskal();
	    printf("%d\n", ans);
	}
    
    return 0;
}

L - 还是畅通工程

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <cstdio>
using namespace std;
const int N = 2e5;
typedef pair<int, int> P;
int bcj[4005];
int n, m, cnt, ans;
struct node {
    int u, v, w;
    inline bool operator < (const node &x) const {
        return w < x.w;
    }
} edge[200005];

int Find(int x)
{
    if(bcj[x] < 0) return x;
    return bcj[x] = Find(bcj[x]);
}

void kruskal()
{
    cnt = ans = 0;
    sort(edge, edge + m);
    for(int i = 0; i < m; ++i) {
        int u = Find(edge[i].u), v = Find(edge[i].v);
        if(u == v) continue;
        ans += edge[i].w;
        bcj[v] = u;
        cnt++;
        if(cnt == n - 1) break;   
    }
}



int main()
{
    while(scanf("%d", &n)!=EOF)
	{
		if(n==0) break;
	    m=n*(n-1)/2;
	    memset(bcj, -1, sizeof bcj);
	    for(int i = 0; i < m; ++i) {
	        scanf("%d %d %d", &edge[i].u, &edge[i].v, &edge[i].w);
	    }
	    kruskal();
	    printf("%d\n", ans);
	}
    return 0;
}

N - 畅通工程再续

链接:https://blog.csdn.net/weixin_43772166/article/details/98885631

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值