UVa 10397 - Connect the Campus
2013-06-23 21:30
344 查看
/*UVa 10397 - Connect the Campus * 把已存在的边权设为0 然后使用Kruscal算法 求最小生成树 * */ import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; class Edge { int u;// 边的起点 int v;// 边的终点 double w;// 边的权重; public Edge(int u, int v, double w) { this.u = u; this.v = v; this.w = w; } } class EdgeComparator implements Comparator<Edge> { @Override public int compare(Edge o1, Edge o2) { if (o1.w < o2.w) return -1; else if (o1.w > o2.w) return 1; return 0; } } class Main { static final int MAXN = 760; Edge[] e = new Edge[MAXN * MAXN]; int[] p = new int[MAXN * MAXN]; double[][] w = new double[MAXN][MAXN]; int[] x = new int[MAXN]; int[] y = new int[MAXN]; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Main mm = new Main(); while (scanner.hasNext()) { int n = scanner.nextInt(); for (int i = 1; i <= n; i++) { mm.x[i] = scanner.nextInt(); mm.y[i] = scanner.nextInt(); } for (int i = 1; i <= n; i++) { for (int j = 1; j <= i; j++) { if (i != j) mm.w[i][j] = mm.w[j][i] = mm.getLength(i, j); } } int m = scanner.nextInt(); for (int i = 0; i < m; i++) { int u = scanner.nextInt(); int v = scanner.nextInt(); mm.w[u][v] = mm.w[v][u] = 0; } int index = 0; for (int i = 1; i <= n; i++) { for (int j = i + 1; j <= n; j++) { mm.e[index++] = new Edge(i, j, mm.w[i][j]); } } for (int i = 0; i <= n * n; i++) {// 并查集初始化 mm.p[i] = i; } double ans = 0; Arrays.sort(mm.e, 0, index, new EdgeComparator());// 按边权排序 for (int i = 0; i < index; i++) { int x = mm.find(mm.e[i].u);//起点 int y = mm.find(mm.e[i].v);//终点 if (x != y) {// 如果不在同一个集合就合并 ans += mm.e[i].w; mm.p[x] = y; } } System.out.printf("%.2f\n", ans); } } private double getLength(int i, int j) { double m = Math.pow(x[i] - x[j], 2); double n = Math.pow(y[i] - y[j], 2); return Math.sqrt(m + n); } private int find(int x) { if (p[x] == x) return x; return p[x] = find(p[x]); } }
相关文章推荐
- UVa 10397 Connect the Campus (Kruskal+补全最小生成树)
- Connect the Campus (Uva 10397 Prim || Kruskal + 并查集)
- UVa 10397 - Connect the Campus
- uva 10397 Connect the Campus kruskal || prim
- UVA 10397 Connect the Campus
- UVa 10397 Connect the Campus
- Connect the Campus (Uva 10397 Prim || Kruskal + 并查集)
- UVA 10397 Connect the Campus
- UVA 10397 - Connect the Campus
- uva 10397 Connect the Campus(最小生成树)
- UVA 10397 - Connect the Campus
- uva 10397 - Connect the Campus
- UVa 10397 - Connect the Campus
- UVA 10397 - Connect the Campus
- UVA 10397 - Connect the Campus
- Uva 10397 - Connect the Campus
- UVA 10397 - Connect the Campus 翻译
- uva 10397 Connect the Campus 把学校连起来
- UVa:10397 Connect the Campus(最小生成树)
- UVA 10397 - Connect the Campus(最小生成树)