Cod sursa(job #2738684)

Utilizator betybety bety bety Data 6 aprilie 2021 11:06:53
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <bits/stdc++.h>
using namespace std;
ifstream in("apm.in");
ofstream out("apm.out");
const int lim=2e5+5;
struct Op
{
    int x;
    int y;
    int c;
};
vector<Op> edges;
vector<pair<int,int> > ans;
int n,m,x,y,c;
bool mycmp(Op a,Op b)
{
    return a.c<b.c;
}
int link[lim];
int dim[lim];
int tata(int x)
{
    int cpy=x,aux;
    while(x!=link[x]) x=link[x];
    while(cpy!=link[cpy]) aux=cpy,cpy=link[cpy],link[aux]=x;
    return x;
}
void unite(int x,int y)
{
    x=tata(x);
    y=tata(y);
    if(dim[x]<dim[y]) swap(x,y);
    dim[x]+=dim[y];
    link[y]=x;
}
int cost;
int main()
{
    in>>n>>m;
    for(int i=1;i<=m;++i)
    {
        in>>x>>y>>c;
        edges.push_back({x,y,c});
    }
    sort(edges.begin(),edges.end(),mycmp);
    for(int i=1;i<=n;++i)
    {
        link[i]=i;
        dim[i]=1;
    }
    for(Op p:edges)
    {
        if(tata(p.x)==tata(p.y))
            continue;
        cost+=p.c;
        ans.push_back({p.x,p.y});
        unite(p.x,p.y);
    }
    out<<cost<<'\n';
    out<<ans.size()<<'\n';
    for(auto p:ans)
        out<<p.first<<' '<<p.second<<'\n';
    return 0;
}