Cod sursa(job #2843809)

Utilizator andreicontorandrei contor andreicontor Data 2 februarie 2022 23:11:42
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 kb
#include<cstdio>
#include<algorithm>
using namespace std;
const int NMax = 400005;
pair <int,int> P[NMax];
int N, M, Total, TT[NMax], k, RG[NMax];
struct Muchie
{
    int x,y,c;
}V[NMax];
bool Compare(Muchie a, Muchie b)
{
    return a.c < b.c;
}
void Read()
{
    scanf("%d%d",&N,&M);
    for(int i = 1; i <= M; i++)
        scanf("%d%d%d",&V[i].x,&V[i].y,&V[i].c);
    sort(V+1, V+M+1, Compare);
}
int Find(int nod)
{
    while(TT[nod] != nod)
        nod = TT[nod];
    return nod;
}
void Unite(int x, int y)
{
    if(RG[x] < RG[y])
        TT[x] = y;
    else
    if(RG[y] < RG[x])
        TT[y] = x;
    else
    {
        TT[x]=y;
        RG[y]++;
    }
}
void Solve()
{
    for(int i=1;i<=M;i++)
    {
        if(Find(V[i].x) != Find(V[i].y))
        {
            k++;
            Unite(Find(V[i].x),Find(V[i].y));
            P[k].first = V[i].x;
            P[k].second = V[i].y;
            Total += V[i].c;
        }
    }
}
int main()
{
    freopen("apm.in","r",stdin);
    freopen("apm.out","w",stdout);
    Read();
    for(int i = 1; i <= M; i++)
    {
        TT[i]=i;
        RG[i]=1;
    }
    Solve();
    printf("%d\n",Total);
    printf("%d\n",N-1);
    for(int i = 1; i <= k; i++)
        printf("%d %d\n",P[i].first,P[i].second);
    return 0;
}