java MLE怎么优化
  • 板块P2121 拆地毯
  • 楼主djisnj
  • 当前回复1
  • 已保存回复1
  • 发布时间2025/2/7 14:19
  • 上次更新2025/2/7 16:22:57
查看原帖
java MLE怎么优化
1421164
djisnj楼主2025/2/7 14:19
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;

public class Main {
    private static int[] parents;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        int k = sc.nextInt();
        List<Edge> edges = new ArrayList<>();
        parents = new int[n + 1];
        for (int i = 1; i <= n; i++) parents[i] = i;
        while (m-- > 0) {
            int from = sc.nextInt();
            int to = sc.nextInt();
            int weight = sc.nextInt();
            edges.add(new Edge(from, to, weight));
        }
        edges.sort(Comparator.comparingInt(o -> -o.weight));
        int ans = 0, count = 0;
        for (Edge e : edges) {
            int x = find(e.from), y = find(e.to);
            if (x != y) {
                parents[x] = y;
                ans += e.weight;
                if (++count == k) break;
            }
        }
        System.out.println(ans);
    }

    private static int find(int x) {
        return x == parents[x] ? x : (parents[x] = find(parents[x]));
    }

    private static class Edge {
        int from, to, weight;

        public Edge(int from, int to, int weight) {
            this.from = from;
            this.to = to;
            this.weight = weight;
        }
    }
}
2025/2/7 14:19
加载中...