问题描述
Farmer John变得非常懒,他不想再继续维护供奶牛之间供通行的道路。道路被用来连接N个牧场,牧场被连续地编号为1到N。每一个牧场都是一个奶牛的家。FJ计划除去P条道路中尽可能多的道路,但是还要保持牧场之间 的连通性。你首先要决定那些道路是需要保留的N-1条道路。第j条双向道路连接了牧场Sj和Ej(1 <= Sj <= N; 1 <= Ej <= N; Sj != Ej),而且走完它需要Lj的时间。没有两个牧场是被一条以上的道路所连接。奶牛们非常伤心,因为她们的交通系统被削减了。你需要到每一个奶牛的住处去安慰她们。每次你到达第i个牧场的时候(即使你已经到过),你必须花去Ci的时间和奶牛交谈。你每个晚上都会在同一个牧场(这是供你选择的)过夜,直到奶牛们都从悲伤中缓过神来。在早上 起来和晚上回去睡觉的时候,你都需要和在你睡觉的牧场的奶牛交谈一次。这样你才能完成你的交谈任务。假设Farmer John采纳了你的建议,请计算出使所有奶牛都被安慰的最少时间。
输入格式
第1行包含两个整数N和P。
接下来N行,每行包含一个整数Ci。
接下来P行,每行包含三个整数Sj, Ej和Lj。
输出格式
输出一个整数, 所需要的总时间(包含和在你所在的牧场的奶牛的两次谈话时间)。
样例输入
5 7
10
10
20
6
30
1 2 5
2 3 5
2 4 12
3 4 17
2 5 15
3 5 6
样例输出
176
数据规模与约定
5 <= N <= 10000,N-1<= P <= 100000,0 <= Lj <= 1000,1 <= Ci <= 1,000。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
class Bian implements Comparable {
private int first, second;
private int value;
public Bian(int first, int second, int value) {
this.first = first;
this.second = second;
this.value = value;
}
public int getFirst() {
return first;
}
public int getSecond() {
return second;
}
public int getValue() {
return value;
}
public int compareTo(Object arg0) {
return value > ((Bian) arg0).value ? 1
: (value == ((Bian) arg0).value ? 0 : -1);
}
}
public class Main1 {
static int min = Integer.MAX_VALUE;
static int father[];
public static void main(String[] args) throws IOException {
ArrayList<Bian> l = new ArrayList<Bian>();
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String s[] = bf.readLine().split(" ");
int n = Integer.parseInt(s[0]);
int m = Integer.parseInt(s[1]);
int d[] = new int[n + 1];
father = new int[n + 1];
for (int i = 1; i <= n; i++) {
father[i] = -1;
d[i] = Integer.parseInt(bf.readLine());
if (min > d[i])
min = d[i];
}
String s1[] = new String[3];
for (int i = 1; i <= m; i++) {
s1 = bf.readLine().split(" ");
int x = Integer.parseInt(s1[0]);
int y = Integer.parseInt(s1[1]);
int w = 2 * Integer.parseInt(s1[2]) + d[x] + d[y];
l.add(new Bian(x, y, w));
}
Collections.sort(l);
int count = 0, sum = 0;
for (int i = 0; i < m; i++) {
if (Union(l.get(i).getFirst(), l.get(i).getSecond())) {
sum += l.get(i).getValue();
count++;
}
if (count == n - 1)
break;
}
System.out.println(sum + min);
}
public static int Find(int x) {
if (father[x] == -1)
return x;
return father[x] = Find(father[x]);
}
public static boolean Union(int x, int y) {
x = Find(x);
y = Find(y);
if (x == y)
return false;
if (x < y)
father[y] = x;
if (y < x)
father[x] = y;
return true;
}
}