Cod sursa(job #2837481)

Utilizator LXGALXGA a LXGA Data 22 ianuarie 2022 10:59:03
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.18 kb
#include <fstream>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
ifstream cin("apm.in");
ofstream cout("apm.out");
struct muchie
{
    int x;
    int y;
    int c;
    friend bool operator<(muchie a,muchie b)
    {
        return a.c>b.c;
    }
};
int t[200001],h[200001];
int f(int x)
{
    int aux=x;
    while(t[x]!=0)
        x=t[x];
    while(t[aux]!=0)
    {
        int xx=t[aux];
        t[aux]=x;
        aux=xx;
    }
    return x;
}

void u(int x,int y)
{
    int xx=f(x),yy=f(y);
    if(h[xx]>h[yy])
        t[yy]=xx;
    else if(h[xx]<h[yy])
        t[xx]=yy;
    else
    {
        t[yy]=xx;
        h[xx]++;
    }
}

int n,m,x,y,c;
vector<pair<int,int>> ans;
priority_queue<muchie> q;
int main()
{
    cin>>n>>m;
    for(int i=1;i<=m;i++)
    {
        cin>>x>>y>>c;
        q.push({x,y,c});
        //g[x].push_back({y,c});
        //g[y].push_back({x,c});
    }
    int sum=0;
	while(!q.empty() && ans.size()<n-1)
	{
		muchie a=q.top();
		q.pop();
		int xx=f(a.x),yy=f(a.y);
		if(xx!=yy)
		{
			ans.push_back({a.x,a.y});
			sum+=a.c;
			u(a.x,a.y);
		}
	}
	cout<<sum<<'\n'<<ans.size()<<'\n';
	for(auto i:ans)
		cout<<i.first<<' '<<i.second<<'\n';
    return 0;
}