【洛谷】 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;
}