ccf历年第四题java解答之-201412-4-最优灌溉(100分)

使用kruskal求解,耗时943ms,得分100

徘徊在超时的边缘,同样的代码,有时候提交是100分,有时候是超时90分,还有时候是超时80分==


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

class Node implements Comparable<Node>{
    public int p1;
    public int p2;
    public int l;

    public Node(int p1, int p2, int l) {
        this.p1 = p1;
        this.p2 = p2;
        this.l = l;
    }

    @Override
    public int compareTo(Node o) {
        return this.l - o.l;
    }
}

public class Main{
    private static int[] v;

    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        String[] firstLine= scanner.nextLine().split(" ");
        int n = Integer.parseInt(firstLine[0]);
        int m = Integer.parseInt(firstLine[1]);
        List<Node> nodes = new ArrayList<>();
        for(int i = 0; i < m; i++){
            String[] line = scanner.nextLine().split(" ");
            int p1 = Integer.parseInt(line[0]);
            int p2 = Integer.parseInt(line[1]);
            int l = Integer.parseInt(line[2]);
            nodes.add(new Node(p1, p2, l));
        }
        scanner.close();

        Collections.sort(nodes);
        v = new int[n + 1];
        for(int i = 0; i < v.length; i++){
            v[i] = i;
        }

        int len = 0;
        while(n > 1){
            Node node = nodes.get(0);
            nodes.remove(node);

            int x = find(node.p1);
            int y = find(node.p2);
            if(x != y){
                len += node.l;
                v[x] = y;
                n--;
            }
        }

        System.out.println(len);
    }

    private static int find(int x){
        while (true){
            if(v[x] == x)
                return x;
            x = v[x];
        }
    }

}

猜你喜欢

转载自blog.csdn.net/qq_23934649/article/details/82142815
今日推荐