題目背景
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
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
int n,m;
long long ans;
struct node{
int x;
int y;
int z;
}a[100005];
int s[100055];
int fa[100005];
int cnt=0;
bool cmp(const node &x,const node &y)
{
return x.z<y.z;
}
int find(int x)
{
if(fa[x]==x)
{
return x;
}
return fa[x]=find(fa[x]);
}
void kkk()
{
int f1;
int f2;
int k=0;
for(int i=1;i<=n;i++)
fa[i]=i;
for(int i=1;i<=cnt;i++)
{
f1=find(a[i].x);
f2=find(a[i].y);
if(f1!=f2)
{
ans=ans+a[i].z;
fa[f1]=f2;
k++;
if(k==n-1)
break;
}
}
}
int main(){
cin>>n;
for(int i=1;i<=n;i++)
{
scanf("%d",&s[i]);
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
scanf("%d",&a[++cnt].z);
a[cnt].x=i;
a[cnt].y=j;
}
a[++cnt].x=i;
a[cnt].y=n+1;
a[cnt].z=s[i];
}
n++;
sort(a+1,a+1+cnt,cmp);
kkk();
cout<<ans<<endl;
}