【洛谷】 P1194 买礼物 的题解

【洛谷】 P1194 买礼物 的题解

题目链接

题解

备战 CSP,复习一下最小生成树,祝大家 rp++!!!

经典的 K r u s k a l Kruskal Kruskal

把所有的物品都看作节点,物品之间的优惠或费用为边的权值,所以要做的就应该是把所有点连接起来的最小代价,也就是求该图的最小生成树。

然后正常建边,按边权跑一遍 K r u s k a l Kruskal Kruskal,就万事大吉了

AC 代码

#include <bits/stdc++.h>
#define lowbit(x) x & (-x)
#define endl "\n"
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
namespace fastIO {
	inline int read() {
		register int x = 0, f = 1;
		register char c = getchar();
		while (c < '0' || c > '9') {
			if(c == '-') f = -1;
			c = getchar();
		}
		while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
		return x * f;
	}
	inline void write(int x) {
		if(x < 0) putchar('-'), x = -x;
		if(x > 9) write(x / 10);
		putchar(x % 10 + '0');
		return;
	}
}
using namespace fastIO;
int a, b, fa[300005], ans = 0, money, tot = 0;
struct node {
	int x, y, z;
}f[300005];
int find(int x) {return x == fa[x] ? x : fa[x] = find(fa[x]);}
bool cmp (node a, node b) {return a.z < b.z;}
int main() {
	//freopen(".in","r",stdin);
	//freopen(".out","w",stdout);
	a = read(), b = read();
	for(int i = 1; i <= b; i ++) {
		fa[i] = i; 
	}
	for(int i = 1; i <= b; i ++) {
		tot ++;
		f[tot].x = 0;
		f[tot].y = i;
		f[tot].z = a;
	} 
	for(int i = 1; i <= b; i ++) {
		for(int j = 1; j <= b; j ++) {
			money = read();
			if(money) {
				tot ++;
				f[tot].x = i;
				f[tot].y = j;
				f[tot].z = money;
			}
		}
	}
	sort(f + 1, f + tot + 1, cmp);
	for (int i = 1; i <= tot; i ++) {
		if (find(f[i].x) != find(f[i].y)) {
			fa[find(f[i].y)] = find(f[i].x);
			ans += f[i].z;
		}
		else continue;
	}
	write(ans);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值