classMain { staticfinalintINF=0x3f3f3f3f; staticfinalintN=100010; staticfinalintM=200010; staticint[] p = newint[N]; staticint[] rank = newint[N]; staticint[][] edges = newint[M][3]; staticint n, m; staticBufferedWriterlog=newBufferedWriter(newOutputStreamWriter(System.out)); staticBufferedReadercin=newBufferedReader(newInputStreamReader(System.in)); // 路径压缩 staticintfind(int x) { if (p[x] != x) p[x] = find(p[x]); return p[x]; } // 按秩合并 staticvoidmerge(int _a, int _b) { inta= find(_a), b = find(_b); // 先保存下来a和b的根节点 if (rank[a] <= rank[b]) { p[a] = b; // 将秩小的根挂到秩较大的根节点上面 } else { p[b] = a; } // 考虑两个集合秩相同的情况下,合并会导致深度加一 if (rank[a] == rank[b] && a != b) { rank[b]++; } }
staticintkruskal() { // 先按照权值排序 Arrays.sort(edges, 0, m, (a, b) -> { return a[0] - b[0]; }); // 初始化 for (inti=1; i <= n; ++i) { p[i] = i; rank[i] = 1; } intres=0, cnt = 0; for (inti=0; i < m; ++i) { inta= edges[i][1]; intb= edges[i][2]; intc= edges[i][0]; // 祖宗节点不同,则不在同一个连通块中 if (find(a) != find(b)) { cnt++; merge(a, b); res += c; } } // 加入的节点少于n-1,说明存在其他连通分量 return cnt < n - 1 ? INF : res; }
publicstaticvoidmain(String[] args)throws Exception { String[] str = cin.readLine().split(" "); n = Integer.parseInt(str[0]); m = Integer.parseInt(str[1]); int a, b, c;
for (inti=0; i < m; ++i) { str = cin.readLine().split(" "); a = Integer.parseInt(str[0]); b = Integer.parseInt(str[1]); c = Integer.parseInt(str[2]);