洛谷 P2121 拆地毯
这道题其实相当于最小生成树的模板题了,想到用最小生成树做是因为题目中描述:保留的地毯构成的图中,任意可互相到达的两点间只能有一种方式互相到达。
其实就是不能有环,因为用一条边连接树中任意两个顶点都会构成一个环,因此就想到了生成树,还有就是题目要求美丽度最大,所以其实是最大生成树。
import java.util.*;
class Edge implements Comparable<Edge>{
int v;
int w;
int weight;
public Edge(int v, int w, int weight) {
this.v = v;
this.w = w;
this.weight = weight;
}
int either() {
return this.v;
}
int other(int v) {
if (this.v == v) {
return this.w;
}
return this.v;
}
// 从大到小排
@Override
public int compareTo(Edge o) {
return o.weight - this.weight;
}
}
class UnionFind {
int[] parent;
int[] size;
int count;
public UnionFind(int n) {
count = n;
parent = new int[n];
size = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
size[i] = 1;
}
}
boolean isConnected(int p, int q) {
return find(p) == find(q);
}
int find(int p) {
while (parent[p] != p) {
p = parent[p];
}
return p;
}
void union(int p, int q) {
int pRoot = find(p);
int qRoot = find(q);
if (pRoot == qRoot) {
return;
}
if (size[pRoot] < size[qRoot]) {
parent[pRoot] = qRoot;
size[qRoot] += size[pRoot];
}
else {
parent[qRoot] = pRoot;
size[pRoot] += size[qRoot];
}
count--;
}
}
class Kruskal {
ArrayDeque<Edge> queue;
PriorityQueue<Edge> pq;
int n;
int k;
public Kruskal(int n, int k, PriorityQueue<Edge> pq) {
queue = new ArrayDeque<>();
this.n = n;
this.k = k;
this.pq = pq;
UnionFind uf = new UnionFind(n);
while (queue.size() < k) {
Edge e = pq.poll();
int v = e.either();
int w = e.other(v);
if (uf.isConnected(v, w)) {
continue;
}
uf.union(v, w);
queue.add(e);
}
}
}
/**
* @author wangshaoyu
*/
public class P2121拆地毯 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt(); // n 个顶点
int m = in.nextInt(); // m 条边
int k = in.nextInt(); // 保留 k 条地毯
PriorityQueue<Edge> pq = new PriorityQueue<>();
for (int i = 0; i < m; i++) {
int v = in.nextInt() - 1;
int w = in.nextInt() - 1;
int weight = in.nextInt();
Edge e = new Edge(v, w, weight);
pq.add(e);
}
Kruskal kru = new Kruskal(n, k, pq);
int ans = 0;
for (Edge e : kru.queue) {
ans += e.weight;
}
System.out.println(ans);
}
}