牛客寒假算法基础集训营4 Applese 的毒气炸弹 (java写最小生成树)

 Applese 的毒气炸弹

链接:https://ac.nowcoder.com/acm/contest/330/G

题目描述


众所周知,Applese 是个很强的选手,它的化学一定很好。

今天他又AK了一套题觉得很无聊,于是想做个毒气炸弹玩。

毒气炸弹需要 k 种不同类型元素构成,Applese一共有 n 瓶含有这些元素的试剂。

已知元素混合遵循 m 条规律,每一条规律都可以用 "x y c" 描述。

表示将第 x 瓶试剂混入第 y 瓶试剂或者把第 y 瓶试剂混入第 x 瓶试剂,需要消耗 c 的脑力。

特别地,除了这 m 条规律外,Applese 可以将任意两瓶相同元素的试剂混合,且不需要消耗脑力。

Applese 想要配出毒气炸弹,就需要使 S 中含有 1k1∼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

备注:

1n,k,m10^5
1x,yn,xy
1c10^9
题解:
最小生成树模板题。注意java中getf函数的写法
static int getf(int x) {
        return f[x]==x?x:getf(f[x]);
}会超时
 static int getf(int x) {
    if(f[x]==x)
         return x;
    else
         return f[x] = getf(f[x]);
 }正确
 1 import java.util.Arrays;
 2 import java.util.Comparator;
 3 import java.util.Scanner;
 4 
 5 class node{
 6     int x;
 7     int y;
 8     long w;
 9 }
10 class mycompare implements Comparator<node>{
11     public int compare(node x,node y) {
12         return (int)(x.w-y.w);
13     }
14 }
15 public class Main { 
16     static final int maxn = 100005;
17     static int n,m,k;
18     static node [] e = new node[maxn];
19     static int [] f = new int [maxn];
20     static int [] a = new int [maxn];
21     static int getf(int x) {
22         if(f[x]==x)
23             return x;
24         else
25             return f[x] = getf(f[x]);
26     }
27     static void merge(int x,int y) {
28         int tx = getf(x);
29         int ty = getf(y);
30         if(tx!=ty) {
31             f[tx] = ty;
32         }
33     }
34     public static void main(String[] args) {
35         Scanner cin = new Scanner(System.in);
36         int flag=0;
37         n = cin.nextInt();
38         m = cin.nextInt();
39         k = cin.nextInt();
40         for(int i=1;i<=n;i++) {
41             a[i] = cin.nextInt();
42             f[i] = i;
43         }
44         for(int i=1;i<=m;i++) {
45             int x = cin.nextInt();
46             int y = cin.nextInt();
47             long w = cin.nextLong();
48             e[i] = new node();
49             e[i].x = a[x];
50             e[i].y = a[y];
51             e[i].w = w;
52         }
53         Arrays.sort(e,1,m+1,new mycompare());
54         int cnt = 0;
55         long sum = 0;
56         for(int i=1;i<=m;i++) {
57             if(getf(e[i].x)!=getf(e[i].y)) {
58                 merge(e[i].x, e[i].y);
59                 cnt++;
60                 sum+=e[i].w;
61             }
62             if(cnt == k-1) {
63                 flag = 1;
64                 break;
65             }    
66         }
67         if(flag==1)
68             System.out.println(sum);
69         else
70             System.out.println(-1);
71     }
72 }

猜你喜欢

转载自www.cnblogs.com/1013star/p/10369887.html
今日推荐