Cod sursa(job #2067425)

Utilizator GeorgeCalinPetruta George-Calin GeorgeCalin Data 16 noiembrie 2017 13:28:19
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.46 kb
#include <fstream>
#include <vector>
#include <algorithm>
#define p pair
#define nmax 200002
using namespace std;

ifstream fin("apm.in");
ofstream fout("apm.out");

p <int,p<int,int> > v[nmax*2];
int t[nmax];
int rg[nmax];
p <int,int> solutie[nmax];

int gaseste(int x)
{
    int r,y;
    r=x;
    while(r!=t[r])
    {
        r=t[r];
    }
    while(x!=t[x])
    {
        y=t[x];
        t[x]=r;
        x=t[x];
    }
    return r;
}

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

int main()
{
    int n,m;
    fin>>n>>m;
    for(int i=1;i<=m;i++)
    {
        fin>>v[i].second.first>>v[i].second.second>>v[i].first;
    }
    for(int i=1;i<=n;i++)
    {
        t[i]=i;
        rg[i]=1;
    }
    sort(v+1,v+m+1);
    int suma=0;
    int nr_muchii=0;
    for(int i=1;i<=m;i++)
    {
        int x=v[i].second.first;
        int y=v[i].second.second;
        int rx=gaseste(x);
        int ry=gaseste(y);
        if(rx!=ry)
        {
            suma+=v[i].first;
            nr_muchii++;
            p <int,int> muchie;
            muchie.first=y;
            muchie.second=x;
            solutie[nr_muchii]=muchie;
            uneste(rx,ry);
        }
    }
    fout<<suma<<"\n"<<nr_muchii<<"\n";
    for(int i=1;i<=nr_muchii;i++)
    {
        fout<<solutie[i].first<<" "<<solutie[i].second<<"\n";
    }
    return 0;
}