Mai intai trebuie sa te autentifici.
Cod sursa(job #3192244)
Utilizator | Data | 11 ianuarie 2024 21:24:41 | |
---|---|---|---|
Problema | Arbore partial de cost minim | Scor | 0 |
Compilator | cpp-64 | Status | done |
Runda | Arhiva educationala | Marime | 1.29 kb |
#include <fstream>
#include <algorithm>
#include <cstring>
#include <vector>
#define nmax 200001
#define mmax 400001
using namespace std;
ifstream cin("apm.in");
ofstream cout("apm.out");
struct muchie
{
int x,y;
signed short int cost;
bool operator < (const muchie &other) const
{
return (cost <= other.cost);
}
};
muchie v[mmax];
vector<muchie> apm;
int tata[nmax], h[mmax], n, m, q, sum;
int rad(int x)
{
int r,y;
r=x;
while(tata[r]!=0)
r=tata[r];
while(tata[x]!=0)
{
y=tata[x];
tata[x]=r;
x=y;
}
return r;
}
int unire(muchie crt)
{
int rx = rad(crt.x);
int ry = rad(crt.y);
if(rx!=ry)
{
sum+=crt.cost;
apm.push_back({crt.x,crt.y,crt.cost});
if(h[rx]==h[ry])
h[ry]++;
if(h[rx]>h[ry])
tata[ry]=rx;
else
tata[rx]=ry;
}
}
int main()
{
cin>>n>>m;
for(int i=1; i<=m; i++)
{
cin>>v[i].x>>v[i].y>>v[i].cost;
}
memset(tata,0,sizeof(tata));
sort(v+1,v+m+1);
for(int i=1; i<=m; i++)
{
unire(v[i]);
}
cout<<sum<<endl<<apm.size()<<endl;
for(auto mcrt : apm)
cout<<mcrt.x<<' '<<mcrt.y<<endl;
}