*N);
    long ans = 0;
    int cnt = 0;

    foreach (e; E) {
        if (uf.find(e[0]) == uf.find(e[1])) continue;
        uf.unite(e[0], e[1]);
        ans += e[2];
        cnt += 1;
        if (cnt == K-1) {
            ans.writeln;
            return;
        }
    }

    writeln(-1);
}


class UnionFind {
    int N;
    int[] table;
    long[] cost;

    this(int n) {
        N = n;
        table = new int[](N);
        fill(table, -1);
        cost = new long[](N);
    }

    int find(int x) {
        return table[x] < 0 ? x : (table[x] = find(table[x]));
    }

    void unite(int x, int y) {
        x = find(x);
        y = find(y);
        if (x == y) return;
        if (table[x] > table[y]) swap(x, y);
        table[x] += table[y];
        table[y] = x;
        cost[x] += cost[y];
    }
}
