P1861 Network java实现 克鲁斯卡尔算法

题目链接:Network

不知道为什么在openjudge上过不去,最后在poj上提交通过了....

顺便说一下,给出的测试用例结果是错误的.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;

public class Main {
static int[] point;

public static void main(String[] args) throws Exception {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    StringTokenizer st = new StringTokenizer(br.readLine());
    int N = Integer.parseInt(st.nextToken());
    int M = Integer.parseInt(st.nextToken());
    Edge[] edges = new Edge[M];
    point = new int[N + 1];
    for (int i = 0; i <= N; i++) {
        point[i] = i;
    }
    PriorityQueue<Edge> pq = new PriorityQueue<Edge>();
    for (int i = 0; i < M; i++) {
        st = new StringTokenizer(br.readLine());
        edges[i] = new Edge(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()));
        pq.add(edges[i]);
    }
    LinkedList<Edge> newEdges = new LinkedList<Edge>();
    Edge pollPoint;
    int maxLength = 0;
    while (!pq.isEmpty()) {
        pollPoint = pq.poll();
        if (!connect(pollPoint.start, pollPoint.end)) {
            union(pollPoint.start,pollPoint.end);
            newEdges.add(pollPoint);
            maxLength = Math.max(pollPoint.conLen, maxLength);
        }
    }
    System.out.println(maxLength);
    System.out.println(newEdges.size());
    StringBuilder bu;
    Collections.sort(newEdges);
    for (Edge edgeRes : newEdges) {
        bu = new StringBuilder();
        bu.append(edgeRes.start).append(" ").append(edgeRes.end);
        System.out.println(bu.toString());
    }
}

public static void union(int a, int b) {
    int A = find(a);
    int B = find(b);
    if (A != B) {
        point[A] = B;
    }
}

public static int find(int a) {
    if (point[a] == a) {
        return point[a];
    } else {
        return point[a] = find(point[a]);
    }
}

public static boolean connect(int a, int b) {
    int A = find(a);
    int B = find(b);
    return A == B;
}

static class Edge implements Comparable<Edge> {
    int start;
    int end;
    int conLen;

    public Edge(int start, int end, int conLen) {
        this.start = start;
        this.end = end;
        this.conLen = conLen;
    }

    @Override
    public int compareTo(Edge edge) {
        if (this.conLen == edge.conLen) {
            return this.start - edge.start;
        } else {
            return this.conLen - edge.conLen;
        }
    }
}

}

posted @ 2021-04-30 16:53  Monstro  阅读(110)  评论(0)    收藏  举报