Cod sursa(job #2868491)

Utilizator Rares5000Baciu Rares Rares5000 Data 10 martie 2022 22:55:36
Problema Arbore partial de cost minim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <bits/stdc++.h>

using namespace std;

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

struct muchie{
    int x, y, c;
}M[400002];

int n, m, R[200002], T[200002], sum, ans[400002], len;

bool Comp(muchie A, muchie B){
    return A.c < B.c;
}

int Find(int x)
{
    if(T[x] == x) return x;
    return Find(T[x]);
}

void Union(int x, int y)
{
    if(R[x] > R[y])
    {
        T[y] = x;
    }
    else if(R[x] < R[y])
    {
        T[x] = y;
    }
    else
    {
        T[x] = y;
        R[x]++;
    }
}

void Afisare()
{
    fout << sum << "\n" << len << "\n";
    for(int i = 1; i <= len; i++)
        fout << M[ans[i]].x << " " << M[ans[i]].y << "\n";
}

int main()
{
    int i;
    fin >> n >> m;
    for(i = 1; i <= m; i++)
        fin >> M[i].x >> M[i].y >> M[i].c;
    sort(M + 1, M + m + 1, Comp);
    for(i = 1; i <= n; i++)
    {
        T[i] = i;
        R[i] = 1;
    }
    for(i = 1; i <= m; i++)
    {
        int t1 = Find(T[M[i].x]);
        int t2 = Find(T[M[i].y]);
        if(t1 != t2)
        {
            Union(t1, t2);
            sum += M[i].c;
            ans[++len] = i;
        }
    }
    Afisare();
    return 0;
}