【模板】最小生成樹-kruskal

joylz發表於2024-11-16
int father[5010], n, m;
int find(int x)//找根函式,記得進行路徑壓縮
{
    if(father[x] == x) return x;
    else return father[x] = find(father[x]);
}
int same(int x, int y)//簡化程式碼
{
    if(find(x) == find(y)) return 1;
    else return 0;
}
struct edge
{
    int u, v, cost;//邊的兩個端點,cost是邊的長度
}e[200010];
int cmp(edge e1, edge e2)
{
    return e1.cost < e2.cost;
}
int kruskal()
{
    sort(e + 1, e + 1 + m, cmp);
    int res = 0;//邊權總和
    int cnt = 0;//邊的數量
    for(int i = 1; i <= m; i++)
    {
        if(same(e[i].u, e[i].v) == 0)
        {
            cnt++;
            res += e[i].cost;
            father[find(e[i].u)] = find(e[i].v);
        }
    }
    if(cnt == n - 1) return res;
    else return -1;
}
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cin >> n >> m;
    for(int i = 1; i <= n; i++)
    {
        father[i] = i;
    }
    for(int i = 1; i <= m; i++)
    {
        cin >> e[i].u >> e[i].v >> e[i].cost;
    }
    int ans = kruskal();
    if(ans == -1) cout << "orz\n";
    else cout << ans << '\n';
    return 0;
}

相關文章