UVA 10369 - Arctic NetWork (求最小生成树)

来源:互联网 发布:centos git 使用 编辑:程序博客网 时间:2024/06/05 18:09

题意:

             在南极有  N  个科研站,要把这些站用卫星和无线电连接起来,是的任意两个之间都能互相通信,如果其中任意的一个地方安装了卫星,那么就可以和其他安装卫星的互相通信,和距离没有关系,但是安装无线电 是需要费用D的,这个费用 D 为在安装无线电的地方中使用的无线电通信花费最大的那个值。现在有S个卫星可以提供给你安装,还有足够多的无线电设备,让你设计一个方案,使得D的费用最少。


思路:

          首先肯定会用到最小生成树。为了使得我们的D值最小那么我们应该给距离最长的 S - 1个路径的俩段安装无线电(因为 S个无线电可以连通S 个科研站,S个科研站有S- 1条路径)。这样的话设最小生成树一共有 K 条边,那么 第 K - S 条排好序的边就是我们要的答案。而 K = N - 1,所以我们最后要求的就是直接求最小生成树的 第 N - S 条边。


代码:


<pre name="code" class="java">import java.util.Scanner;import java.util.Comparator;import java.util.Arrays;import java.text.DecimalFormat;class Node{public int u, v, mark;public double w;}class Points{public double x;public double y;}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 = 250000 + 13;final static int INF = 0x3f3f3f3f;static int[] pre = new int[MAXN];static Node[] map = new Node[MAXN];static Points[] pit = new Points[MAXN];public static void main(String[] args){Scanner sc = new Scanner(System.in);int T = sc.nextInt();while(T != 0){int S, P;S = sc.nextInt();P = sc.nextInt();mst(P);for(int i = 1; i <= P; i++){pit[i] = new Points();pit[i].x = sc.nextInt();pit[i].y = sc.nextInt();}int len = 1;for(int i = 1; i < P; i++){for(int j = i + 1; j <= P; j++){map[len] = new Node();map[len].u = i;map[len].v = j;map[len].w = dist(pit[i], pit[j]);len++;}}Arrays.sort(map, 1, len,  new mycmp());int k = P - S;  //第 K 条边就是答案double ans = ksu(P, len, k);DecimalFormat df = new DecimalFormat("0.00");String db = df.format(ans);System.out.println(db);T--;}sc.close();}public static double dist(Points a, Points b){return Math.sqrt( (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y) );}public static double ksu(int N, int M, int k){ int cnt = 0;double ans = map[M - 1].w;//初始化为最大的那条边for(int i = 1; i < M; i++){int fu = Find(map[i].u);int fv = Find(map[i].v);if(fu != fv){cnt++;if(cnt == k){ //找到第K条边ans = map[i].w;}pre[fv] = fu;map[i].mark = 1;   }}return ans;}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;}}}





0 0
原创粉丝点击