牛客寒假算法基础集训营4 Applese 的毒气炸弹 /*最小生成树(并查集实现) 并查集模板*/
链接: https://ac.nowcoder.com/acm/contest/330/G来源:牛客网
时间限制:C/C++ 2秒,其他语言4秒
空间限制:C/C++ 262144K,其他语言524288K
64bit IO Format: %lld题目描述
众所周知,Applese 是个很强的选手,它的化学一定很好。
今天他又AK了一套题觉得很无聊,于是想做个毒气炸弹玩。
毒气炸弹需要 k 种不同类型元素构成,Applese一共有 n 瓶含有这些元素的试剂。
已知元素混合遵循 m 条规律,每一条规律都可以用 "x y c" 描述。
表示将第 x 瓶试剂混入第 y 瓶试剂或者把第 y 瓶试剂混入第 x 瓶试剂,需要消耗 c 的脑力。
特别地,除了这 m 条规律外,Applese 可以将任意两瓶相同元素的试剂混合,且不需要消耗脑力。
Applese 想要配出毒气炸弹,就需要使 S 中含有 1∼k1∼k 这 k 种元素。它想知道自己最少花费多少脑力可以把毒气炸弹做出来。
输入描述:
第一行为三个整数 n, m, k 表示 Applese 拥有的试剂的数量,混合规律的数量和所需的元素种类数。 第二行为 n 个整数 a1,a2,…,ana1,a2,…,an,分别表示每一瓶试剂的元素类型。 接下来m行,每行三个整数 x, y, c,含义如题目描述中所述。不保证 x, y的试剂种类不同。
输出描述:
输出一个正整数表示最小的耗费脑力。特别地,如果无法合成出毒气炸弹,输出 "-1"。
示例1
输入
复制
6 8 2 1 1 1 2 2 2 1 2 1 2 3 2 1 3 3 3 4 6 4 5 1 4 6 3 5 6 2 1 6 2
输出
复制
2
备注:
1≤n,k,m≤10^5 1≤n,k,m≤10^5 1≤x,y≤n,x≠y1≤x,y≤n,x≠y 1≤c≤10^9
最小生成树,用克里斯卡尔算法,并查集实现。
(不是很懂相同试剂放一起的输入有什么用。。。绕)
/*08/02/19 16:32*/
#include<iostream>
#include<algorithm>
#include<vector>
#include<cstdio>
using namespace std;
#define LL long long
struct no{
int x,y,c;
};
bool operator<(const no &x,const no &y){
return x.c<y.c;
}
int pre[100005];
int found(int x){
int r=x;
while(r!=pre[r]){
r=pre[r];
}
while(x!=pre[x]){
int j=pre[x];
pre[x]=r;
x=j;
}
return r;
}
bool join(int x,int y){
int fx=found(x),fy=found(y);
if(fx!=fy) {
pre[fx]=fy;
return 0;
}
return 1;
}
int main(){
int n,m,k;
cin>>n>>m>>k;
int a[100005];
no arc[100005];
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
}
for(int i=1;i<=m;i++){
scanf("%d%d%d",&arc[i].x,&arc[i].y,&arc[i].c);
}
for(int i=1;i<=100004;i++)
pre[i]=i;
sort(arc+1,arc+1+m);
LL re=0;
for(int i=1;i<=m;i++){
if(join(a[arc[i].x],a[arc[i].y])==0)
re=re+(LL)arc[i].c;
}
for(int i=2;i<=k;i++){
if(found(i)!=found(1)) re=-1;
}
cout<< re;
}