Cod sursa(job #2963137)

Utilizator andreibazavanAndrei Bazavan andreibazavan Data 10 ianuarie 2023 09:41:01
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <bits/stdc++.h>

using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
#define nmax 400005
int n,m,i;
int h[nmax];
int sol[nmax][2];

struct muchie
{
    int x,y,c;
} v[nmax];
int t[nmax];
bool comp(muchie a,muchie b)
{
    return a.c<b.c;

}
int tata(int x)
{
    int aux=x;

    while(x!=t[x])x=t[x];
    while(aux!=x)
    {
        aux=t[aux];
        t[aux]=x;

    }
    return x;

}
int nr,cost;
void unionn(int x, int y)
{
    if(h[x]>h[y])t[y]=x;
    else
    {
        t[x]=y;
        if(h[x]==h[y])h[y]++;
    }
}
int main()
{
    fin>>n>>m;
    for(i=1; i<=m; i++)
    {
        fin>>v[i].x>>v[i].y>>v[i].c;
        t[i]=i;
        h[i]=1;
    }
    sort(v+1,v+m+1,comp);
    for(i=1; i<=m; i++)
    {
        int st=v[i].x;
        int dr=v[i].y;
        st=tata(st);
        dr=tata(dr);
        if(st!=dr)
        {
            unionn(st,dr);
            sol[++nr][0]=v[i].x;
            sol[nr][1]=v[i].y;
            cost+=v[i].c;
        }
    }
    fout<<cost<<'\n'<<nr<<'\n';
    for(i=1; i<=nr; i++)
    {
        fout<<sol[i][0]<<" "<<sol[i][1]<<'\n';
    }
    return 0;
}