Cod sursa(job #2346433)

Utilizator HaesteinnSabau Florin Vlad Haesteinn Data 17 februarie 2019 18:03:29
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 kb
#include<bits/stdc++.h>
#define NMAX 200005
#define MMAX 400005
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
int n,m;
int link[NMAX],height[NMAX];

struct edge
{
    int w,a,b;
    bool operator<(const edge &e)
    {
        return this->w<e.w;
    }
};


void initializeDisjoint()
{
    for(int i=1;i<=n;i++)
        link[i]=i;
}

int find(int x)
{
    while(x!=link[x]) x=link[x];
    return x;
}

bool same(int a,int b)
{
    return find(a)==find(b);
}

void unite(int a,int b)
{
    a=find(a);
    b=find(b);
    if(height[a]>height[b])
        swap(a,b);
    link[a]=b;
    height[b]=max(height[b],height[a]+1);
}

int main()
{
    fin>>n>>m;
    initializeDisjoint();
    vector<edge> v;
    int cst=0;
    vector<pair<int,int> > ans;
    for(int i=0;i<m;i++)
    {
        int w,a,b;
        fin>>a>>b>>w;
        v.push_back({w,a,b});
    }
    sort(v.begin(),v.end());
    for(auto x:v)
    {
        if(!same(x.a,x.b))
        {
            cst+=x.w;
            ans.push_back({x.a,x.b});
            unite(x.a,x.b);
        }
    }
    fout<<cst<<'\n'<<ans.size()<<'\n';
    for(auto x:ans)
        fout<<x.first<<" "<<x.second<<'\n';
    return 0;
}