Cod sursa(job #2384624)

Utilizator alexdumitrescuDumitrescu George Alex alexdumitrescu Data 20 martie 2019 22:28:55
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 kb
#include <fstream>
#include <algorithm>
#include <vector>

#define Nmax 200005
using namespace std;
ifstream fin ("apm.in");
ofstream fout ("apm.out");
int t[Nmax], s[Nmax], i, j, M, n, sum;
struct muchie
{
    int x, y, c;
};
muchie m[2*Nmax];
vector <muchie> v;
bool criteriu(muchie a, muchie b)
{
    return a.c<b.c;
}
void uneste(int x, int y)
{
    if(s[x]>=s[y])
    {
        t[y]=x;
        s[x]+=s[y];
    }
    else
    {
        t[x]=y;
        s[y]+=s[x];
    }
}
int gaseste(int x)
{
    if(t[x]!=x)
        t[x]=gaseste(t[x]);
    return t[x];
}
int main()
{
    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, criteriu);
    for(i=1;i<=n;i++)
    {
        t[i]=i;
        s[i]=1;
    }
    for(i=1;i<=M;i++)
    {
        gaseste(m[i].x);
        gaseste(m[i].y);
        if(t[m[i].x]!=t[m[i].y])
        {
            v.push_back(m[i]);
            sum+=m[i].c;
            uneste(t[m[i].x], t[m[i].y]);
        }
    }
    fout << sum << '\n' << n-1 << '\n';
    for(i=0;i<n-1;i++)
        fout << v[i].x << ' ' << v[i].y << '\n';
    return 0;
}