您的位置:首页 > 其它

UVA Live 6437 Power Plant 最小生成树

2016-04-03 11:31 330 查看
题意:

有许多油井和村庄什么的,让你使得这些村庄能连通一个油井就好了。第一行给你一个数字T代表有T组测试数据,第二行有 M , N , K ,M代表包括油井在内的村庄数,N 代表有N个 两两连通的地方。K代表有K个油井。接下来有N行,每行三个数 u , v, w, 代表 u 号和 v 是连通的 权值为 w。

思路:

以往做的题目都是只有一个源点,这道题油井的数目就是源点,所以源点不唯一。但是不要想复杂啦、其实一开始直接让所有源点并在一、再求最小生成树就好了。

代码:

import java.util.Scanner;
import java.util.Comparator;
import java.util.Arrays;
import java.text.DecimalFormat;

class Node{
public int u, v;
public int w;
}

class mycmp implements  Comparator<Node>{
public int compare(Node A, Node B){
if(A.w == B.w) return 0;
else if(A.w < B.w) return -1;
else return 1;
}
}

public class Main {
final static int MAXN = 40000 + 13;
final static int INF = 0x3f3f3f3f;
static int[] pre = new int[MAXN];
static Node[] map = new Node[MAXN];
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
int kas = 1;
while(T != 0){
int N = sc.nextInt();
int M = sc.nextInt();
int K = sc.nextInt();
int power = sc.nextInt();
mst(N);
for(int i = 0; i < K - 1; i++){
int num = sc.nextInt();
pre[num] = power;
}
for(int i = 1; i <= M; i++){
map[i] = new Node();
map[i].u = sc.nextInt();
map[i].v = sc.nextInt();
map[i].w = sc.nextInt();
}
Arrays.sort(map, 1, M + 1,  new mycmp());
int ans = ksu(N, M, K);
System.out.println("Case #" + kas + ": " + ans);
kas++;
T--;
}
sc.close();
}
public static int ksu(int N, int M, int k){
int cnt = 0;
int ans = 0;
for(int i = 1; i <= M; i++){
int fu = Find(map[i].u);
int fv = Find(map[i].v);
if(fu != fv){
cnt++;
pre[fv] = fu;
ans += map[i].w;
}
if(cnt == N - k){
return ans;
}
}
return 0;
}
public static int Find(int x){
return x == pre[x] ? x : (pre[x] = Find(pre[x]));
}
public static void mst(int N){
for(int i = 1; i <= N; i++){
pre[i] = i;
}
}
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: