L i n k Link Link
D e s c r i p t i o n Description Description
Farmer John已经决定把水灌到他的n块农田,农田被数字1到n标记。把一块土地进行灌水有两种方法,从其他农田饮水,或者这块土地建造水库。
建造一个水库需要花费wi,连接两块土地需要花费Pij.
计算Farmer John所需的最少代价。
I n p u t Input Input
*第一行:一个数n
*第二行到第n+1行:第i+1行含有一个数wi
*第n+2行到第2n+1行:第n+1+i行有n个被空格分开的数,第j个数代表pij。
O u t p u t Output Output
*第一行:一个单独的数代表最小代价.
S a m p l e Sample Sample I n p u t Input Input
4
5
4
4
3
0 2 2 2
2 0 3 3
2 3 0 4
2 3 4 0
S a m p l e Sample Sample O u t p u t Output Output
9
H i n t Hint Hint
T r a i n Train Train o f of of T h o u g h t Thought Thought
设一个零号点与每个点连接,权值为造水库的代价
然后跑一遍最小生成树就好了
(然而我这菜鸡还是错了)
C o d e Code Code
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int x, y, z, t, n, k, ans;
int fa[505];
struct node
{
int w, h, k;
}w[200005];
int find(int k)
{
while (fa[k] != k) k = fa[k];
return k;
}
bool nm (node i, node j)
{return i.k < j.k;}
void add (int x, int y, int z)
{w[++t] = (node){y, x, z};}
int main()
{
scanf("%d", &n);
fa[0] = 0;
for (int i = 1; i <= n; ++i)
{
scanf("%d", &k);
add(0, i, k);
fa[i] = i;
}
for (int i = 1; i <= n ;++i)
for (int j = 1; j <= n; ++j)
{
scanf("%d", &k);
if (i < j) add(i, j , k);
}
sort(w + 1, w + t + 1, nm);
for (int i = 1; i <= t; ++i)
{
x = find(w[i].w);
y = find(w[i].h);
if (x != y)
{
fa[max(x, y)] = fa[min(x, y)];
ans += w[i].k;
}
}
printf("%d",ans);
return 0;
}