Cod sursa(job #3364694)

Utilizator andrei22116Popescu Stefan Andrei andrei22116 Data 9 septembrie 2026 09:49:39
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <bits/stdc++.h>

using namespace std;

int n,m;

struct Cows{
int x;
int y;
int c;
};
Cows muc[400005];

int parent[200005];
int sz[200005];
int rez[200005];

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

void unite(int x,int y)
{
    x=Find(x);
    y=Find(y);
    if(sz[x]<sz[y])
        swap(x,y);
    parent[y]=x;
    sz[x]+=sz[y];
    sz[y]=0;
}

bool cmp(Cows a,Cows b)
{
    return a.c<b.c;
}

int main()
{
    ifstream cin("apm.in");
    ofstream cout("apm.out");
    cin >> n >> m;
    for(int i=1;i<=n;i++)
    {
        parent[i]=i;
        sz[i]=1;
    }
    int a,b,cost;
    for(int i=1;i<=m;i++)
    {
        cin >> a >> b >> cost;
        muc[i].x=a;
        muc[i].y=b;
        muc[i].c=cost;
    }
    sort(muc+1,muc+m+1,cmp);
    cost=0;
    int cnt=0;
    for(int i=1;i<=m;i++)
    {
        if(cnt==n)
            break;
        if(Find(muc[i].x)!=Find(muc[i].y))
        {
            rez[++cnt]=i;
            unite(muc[i].x,muc[i].y);
            cost+=muc[i].c;
        }
    }
    cout << cost << '\n' << n-1 << '\n';
    for(int i=1;i<=cnt;i++)
    {
        cout << muc[rez[i]].x << " " << muc[rez[i]].y << '\n';
    }
    return 0;
}