Cod sursa(job #3251301)

Utilizator staicumateiStaicu Matei Octavian staicumatei Data 25 octombrie 2024 16:56:52
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.19 kb
#include <bits/stdc++.h>
using namespace std;
ifstream f("apm.in");
ofstream g("apm.out");

int x, y, c, r[200005], t[200005], n, m;
pair <int, int> a[400005];

struct mm
{
    int x, y, c;
};

int caut(int x)
{
    if (t[x]==0)
        return x;
    return t[x]=caut(t[x]);
}

int cmp (mm a, mm b)
{
    if (a.c<b.c)
        return 1;
    return 0;
}

void unire(int x, int y)
{
    if (r[x]>r[y])
    {
        t[y]=x;
        r[x]+=r[y];
    }
    else
    {
        t[x]=y;
        r[y]+=r[x];
    }
}

mm v[400005];

int main()
{
    int i, x1, y1,cm=0,nr=0,cnt=0;
    f>>n>>m;
    for (i=1;i<=m;i++)
    {
        f>>v[i].x>>v[i].y>>v[i].c;
    }
    sort (v+1,v+m+1,cmp);
    for (i=1;i<=m;i++)
    {
        x1 = v[i].x;
        y1 = v[i].y;
        x1 = caut(x1);
        y1 = caut(y1);
        if (x1 != y1)
        {
            cnt++;
            a[++nr]={v[i].x, v[i].y};
            cm += v[i].c;
            unire(x1, y1);
        }
            if(cnt==n-1)
                break;
    }
    g << cm <<endl;
    g << nr <<endl;
    for (i = 1 ; i <= nr ; i++)
        g<<a[i].first<<" "<<a[i].second<<endl;
        return 0;
}