展开
题目背景
John的农场缺水了!!!
题目描述
Farmer John has decided to bring water to his N (1 <= N <= 300) pastures which are conveniently numbered 1…N. He may bring water to a pasture either by building a well in that pasture or connecting the pasture via a pipe to another pasture which already has water.
Digging a well in pasture i costs W_i (1 <= W_i <= 100,000).
Connecting pastures i and j with a pipe costs P_ij (1 <= P_ij <= 100,000; P_ij = P_ji; P_ii=0).
Determine the minimum amount Farmer John will have to pay to water all of his pastures.
POINTS: 400
农民John 决定将水引入到他的n(1<=n<=300)个牧场。他准备通过挖若
干井,并在各块田中修筑水道来连通各块田地以供水。在第i 号田中挖一口井需要花费W_i(1<=W_i<=100,000)元。连接i 号田与j 号田需要P_ij (1 <= P_ij <= 100,000 , P_ji=P_ij)元。
请求出农民John 需要为使所有农场都与有水的农场相连或拥有水井所需要的钱数。
输入格式
第1 行为一个整数n。
第2 到n+1 行每行一个整数,从上到下分别为W_1 到W_n。
第n+2 到2n+1 行为一个矩阵,表示需要的经费(P_ij)。
输出格式
只有一行,为一个整数,表示所需要的钱数。
输入输出样例
输入 #1复制
4
5
4
4
3
0 2 2 2
2 0 3 3
2 3 0 4
2 3 4 0
输出 #1复制
9
说明/提示
John等着用水,你只有1s时间!!!
思路: 最小生成树
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
typedef long long ll;
#define INF 0x3f3f3f3f
const ll maxn = 2e6 + 7;
struct Edge
{
ll x,y;
ll w;
}edges[maxn];
ll fa[maxn];
ll findset(ll x)
{
if(fa[x] == x)return x;
return fa[x] = findset(fa[x]);
}
ll cmp(Edge a,Edge b)
{
return a.w < b.w;
}
int main()
{
ll n;scanf("%lld",&n);
ll cnt = 0;
for(ll i = 1;i <= n;i++)
{
ll x;scanf("%lld",&x);
edges[++cnt].x = 0;edges[cnt].y = i;edges[cnt].w = x;
fa[i] = i;
}
for(ll i = 1;i <= n;i++)
{
for(ll j = 1;j <= n;j++)
{
ll tmp;
scanf("%lld",&tmp);
if(i == j)continue;
edges[++cnt].x = i;edges[cnt].y = j;edges[cnt].w = tmp;
}
}
sort(edges + 1,edges + 1 + cnt,cmp);
ll ans = 0;
ll num = 0;
for(ll i = 1;i <= cnt;i++)
{
ll ri = findset(edges[i].x),rj = findset(edges[i].y);
if(ri != rj)
{
fa[ri] = rj;
ans += edges[i].w;
num++;
}
else continue;
if(num >= n)
break;
}
printf("%lld\n",ans);
return 0;
}