网络布线

题目

描述 Description
农民约翰被选为他们镇的镇长!他其中一个竞选承诺就是在镇上建立起互联网,并连接到所有的农场。当然,他需要你的帮助。约翰已经给他的农场安排了一条高速的网络线路,他想把这条线路共享给其他农场。为了用最小的消费,他想铺设最短的光纤去连接所有的农场。你将得到一份各农场之间连接费用的列表,你必须找出能连接所有农场并所用光纤最短的方案。每两个农场间的距离不会超过100000
输入格式 Input Format
第一行: 农场的个数,N(3<=N<=100)。
第二行…结尾: 后来的行包含了一个N*N的矩阵,表示每个农场之间的距离。当然,对角线将会是0,因为不会有线路从第i个农场到它本身。
输出格式 Output Format
只有一个输出,其中包含连接到每个农场的光纤的最小长度。
样例输入 Sample Input
4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0
样例输出 Sample Output
28

题解

prim最小生成树的思想。
模板题?
只是为了水博客,实在闲的无聊,毕竟我这么菜

code

#include <algorithm>
#include <cctype>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstring>
#include <deque>
#include <functional>
#include <list>
#include <map>
#include <iomanip>    
#include <iostream>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;
const int maxn = 150;
typedef long long ull;

inline int read() {
	int s = 0, w = 1;
	char ch = getchar();
	while (!isdigit(ch)) { if (ch == '-') w = -1; ch = getchar(); }
	while (isdigit(ch)) { s = (s << 1) + (s << 3) + (ch ^ 48); ch = getchar(); }
	return s * w;
}

int n;
int x;
int ans;
int dis[maxn];
int f[maxn][maxn];
const int inf = 0x3f3f3f3f;
bool vis[maxn];

int main() {
	n = read();
	memset(vis, false, sizeof(vis));
	for (int i = 1; i <= n; ++i) {
		for (int j = 1; j <= n; ++j) {
			f[i][j] = read();
		}
	}
	vis[1] = true; ans = 0;
	for (int i = 2; i <= n; ++i) {
		dis[i] = f[1][i];
	}
	while (true) {
		int k = 666, kmin = inf; //emm 因为n最多到100所以k设成666也无所谓(最好设为0!)
		for (int i = 1; i <= n; ++i) {
			if (!vis[i] && dis[i] < kmin) {
				kmin = dis[i];
				k = i;
			}
		}
		if (k == 666) break;
		vis[k] = 1;
		ans += dis[k];
		for (int i = 1; i <= n; ++i) {
			if (!vis[i] && (dis[i] > f[k][i])) {
				dis[i] = f[k][i];
			}
		}
	}
	printf("%d\n", ans);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值