Cod sursa(job #3344193)

Utilizator Costy2345Costi Dimian Costy2345 Data 1 martie 2026 16:47:04
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.47 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("apm.in");
ofstream fout("apm.out");

const int NMAX = 2e5 + 2;
int n, m, tata[NMAX], s[NMAX];
vector<tuple<int, int, int>> edges;

int findRoot(int nod)
{
    int root = nod;
    while(tata[root] != root)
    {
        root = tata[root];
    }
    while(tata[nod] != root)
    {
        int temp = tata[nod];
        tata[nod] = root;
        nod = temp;
    }
    return root;
}

int main()
{
    fin >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        int x, y, cost;
        fin >> x >> y >> cost;
        edges.push_back({cost, x, y});
    }
    sort(edges.begin(), edges.end());
    vector<pair<int, int>> sol;

    // DSU 
    for(int i = 1; i <= n; i++)
    {
        tata[i] = i;
        s[i] = 1;
    }
    int sum = 0;
    for(auto [cost, x, y]: edges)
    {
        if(findRoot(x) != findRoot(y))
        {
            sum += cost;
            sol.push_back({x, y});  
            cout << x << " " << y << " cu root " << findRoot(x) << " " << findRoot(y) << "\n";
            if(s[x] <= s[y])
            {
                tata[findRoot(x)] = findRoot(y);
                s[y] += s[x];
            }
            else{
                tata[findRoot(y)] = findRoot(x);
                s[x] += s[y];
            }
        }
    }
    fout << sum << "\n" << n - 1 << "\n";
    for(auto [x, y]: sol)
    {
        fout << x << " " << y << "\n";
    }
    return 0;
}