当前位置:   article > 正文

AtCoder 328. E Modulo MST_e - modulo mst

e - modulo mst

暴力枚举所有选边的可能, 最后再判断是否是连通图

  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import java.util.Scanner;
  4. class Main {
  5. static class Edge {
  6. int a, b;
  7. long w;
  8. public Edge(int a, int b, long w) {
  9. this.a = a;
  10. this.b = b;
  11. this.w = w;
  12. }
  13. }
  14. static int n, m;
  15. static long k, ans = Long.MAX_VALUE;
  16. static Edge[] e;
  17. static List<Edge> lis = new ArrayList<>();
  18. static int[] p;
  19. public static int find(int x) {
  20. if (x != p[x]) p[x] = find(p[x]);
  21. return p[x];
  22. }
  23. public static void add(int x, int y) {
  24. int px = find(x), py = find(y);
  25. if (px == py) return ;
  26. p[px] = py;
  27. }
  28. public static void main(String[] args) {
  29. Scanner sc = new Scanner(System.in);
  30. n = sc.nextInt(); m = sc.nextInt(); k = sc.nextLong();
  31. e = new Edge[m + 10];
  32. p = new int[n + 10];
  33. for (int i = 1; i <= m; i ++ ) {
  34. int x = sc.nextInt(); int y = sc.nextInt(); long c = sc.nextLong();
  35. e[i] = new Edge(x, y, c);
  36. }
  37. dfs(1, 0);
  38. System.out.println(ans);
  39. }
  40. public static void dfs(int now, int x) {
  41. if (x == n - 1) {
  42. long sum = 0;
  43. for (int i = 1; i <= n; i ++ ) p[i] = i; // 并查集的初始化
  44. // 用并查集判断是否是连通图
  45. for (int i = 0; i < lis.size(); i ++ ) {
  46. Edge t = lis.get(i);
  47. sum += t.w;
  48. add(t.a, t.b);
  49. }
  50. for (int i = 2; i <= n; i ++ ) {
  51. if (find(i) != find(i - 1)) return ;
  52. }
  53. ans = Math.min(ans, sum % k); // 尝试更新答案
  54. return ;
  55. }
  56. if (now >= m + 1) return ;
  57. dfs(now + 1, x);
  58. lis.add(e[now]);
  59. dfs(now + 1, x + 1);
  60. lis.remove(e[now]);
  61. }
  62. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/74434?site
推荐阅读
相关标签
  

闽ICP备14008679号