暴力枚举所有选边的可能, 最后再判断是否是连通图
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Main {
static class Edge {
int a, b;
long w;
public Edge(int a, int b, long w) {
this.a = a;
this.b = b;
this.w = w;
}
}
static int n, m;
static long k, ans = Long.MAX_VALUE;
static Edge[] e;
static List<Edge> lis = new ArrayList<>();
static int[] p;
public static int find(int x) {
if (x != p[x]) p[x] = find(p[x]);
return p[x];
}
public static void add(int x, int y) {
int px = find(x), py = find(y);
if (px == py) return ;
p[px] = py;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt(); m = sc.nextInt(); k = sc.nextLong();
e = new Edge[m + 10];
p = new int[n + 10];
for (int i = 1; i <= m; i ++ ) {
int x = sc.nextInt(); int y = sc.nextInt(); long c = sc.nextLong();
e[i] = new Edge(x, y, c);
}
dfs(1, 0);
System.out.println(ans);
}
public static void dfs(int now, int x) {
if (x == n - 1) {
long sum = 0;
for (int i = 1; i <= n; i ++ ) p[i] = i; // 并查集的初始化
// 用并查集判断是否是连通图
for (int i = 0; i < lis.size(); i ++ ) {
Edge t = lis.get(i);
sum += t.w;
add(t.a, t.b);
}
for (int i = 2; i <= n; i ++ ) {
if (find(i) != find(i - 1)) return ;
}
ans = Math.min(ans, sum % k); // 尝试更新答案
return ;
}
if (now >= m + 1) return ;
dfs(now + 1, x);
lis.add(e[now]);
dfs(now + 1, x + 1);
lis.remove(e[now]);
}
}