Cod sursa(job #3237024)

Utilizator Sasha_12454Eric Paturan Sasha_12454 Data 4 iulie 2024 09:23:48
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.74 kb
#include <bits/stdc++.h>

std :: ifstream in ("apm.in");

std :: ofstream out ("apm.out");

const int NMAX = 2e5 + 5;

int n;

int m;

int x;

int y;

int d;

int sum;

int rank[NMAX];

int parent[NMAX];

std :: vector <std :: pair <int, std :: pair <int, int>>> v;

std :: stack <std :: pair <int, int>> ans;

int getroot(int x)
{
    if(parent[x] == x)
    {
        return x;
    }

    parent[x] = getroot(parent[x]);

    return parent[x];
}

void union_set(int x, int y)
{
    if(rank[x] > rank[y])
    {
        parent[y] = x;
    }
    else if(rank[x] < rank[y])
    {
        parent[x] = y;
    }
    else
    {
        parent[y] = x;

        rank[x] ++;
    }
}

int main()
{

    in >> n >> m;

    for(int i = 1; i <= m; i ++)
    {
        in >> x >> y >> d;

        v.push_back(std :: make_pair(d, std :: make_pair(x, y)));
    }

    for(int i = 1; i <= n; i ++)
    {
        parent[i] = i;
    }

    std :: sort(v.begin(), v.end());

    std :: reverse(v.begin(), v.end());

    /*for(auto i : v)
    {
        std :: cout << i.first << " ";
    }*/

    n --;

    while(n)
    {
        d = v.back().first;

        x = v.back().second.first;

        y = v.back().second.second;

        int aux = getroot(x);

        int aux1 = getroot(y);

        if(aux != aux1)
        {
            ans.push(std :: make_pair(x, y));

            union_set(aux, aux1);

            sum += d;

            n --;
        }

        v.pop_back();
    }

    out << sum << '\n';

    out << ans.size() << '\n';

    while(!ans.empty())
    {
        out << ans.top().first << " " << ans.top().second << '\n';

        ans.pop();
    }

    return 0;
}