예제 #1
0
vvii mst(int V, viii &E) {
    vvii G(V);
    union_find uf(V);
    sort(E.begin(), E.end());
    iter(it, E) {
        int x = (*it).S.F;
        int y = (*it).S.S;
        if(uf.unite(x, y)) {
            G[x].push_back(ii(y, (*it).F));
            G[y].push_back(ii(x, (*it).F));
        }
    }
 lld kruskal(lld idx) {
   UnionFind UF(n);
   vii MST; //Contiene las aristas del MST
   sort(edges.begin(), edges.end());
   lld mx = -INF;
   for (lld i = idx; i < edges.size(); i++) {
     lld w = edges[i].fst;
     lld a = edges[i].snd.fst;
     lld b = edges[i].snd.snd;
     if (!UF.isSameSet(a, b)) {
       MST.push_back(edges[i].snd);
       mx = max(mx, w);
       UF.Union(a, b);
     }
   }
   //Existencia de MST:
   return (UF.numSet() != 1) ? -1 : mx; // costo del MST
 }
vii kruskal(viii &edges, int n, int m) {
	vii ret;
	UnionFind ds(n);

	sort(edges.begin(), edges.end());

	for (int i = 0; i < m; i++) {
		int w = edges[i].st;
		int u = edges[i].nd.st;
		int v = edges[i].nd.nd;

		if (ds._find(u) != ds._find(v)) {
			ds._union(u, v);
			ret.push_back({min(u, v), max(u, v)});
		}
	}

	return ret;
}