Cod sursa(job #2173364)

Utilizator GeorgeCalinPetruta George-Calin GeorgeCalin Data 15 martie 2018 21:52:40
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.79 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]++;
}

inline int citnr()
{
    char c;
    int nr=0,sgm=1;
    c=fin.get();
    if(c=='-')
        sgm=-1;
    else
        nr=nr*10+c-'0';
    c=fin.get();
    while(c>='0'&&c<='9')
    {
        nr=nr*10+c-'0';
        c=fin.get();
    }
    return nr*sgm;
}

int main()
{
    int n,m;
    fin>>n>>m;
    char c=fin.get();
    for(int i=1;i<=m;i++)
    {
        v[i].second.first=citnr();
        v[i].second.second=citnr();
        v[i].first=citnr();
    }
    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;
}