Pagini recente » Cod sursa (job #3291440) | Cod sursa (job #1290563) | Cod sursa (job #842983) | Cod sursa (job #2047891) | Cod sursa (job #2901964)
#include <fstream>
#include <algorithm>
using namespace std;
int t[200005],h[200005];
struct numere{
int x,y,cost,val;
}v[400005];
bool cmp(numere a,numere b){
return a.cost<b.cost;
}
int find1(int x){
while(t[x]!=x){
x=t[x];
}
return x;
}
void union1(int x,int y){
if(h[x]>h[y]){
t[y]=x;
}
else if(h[y]>h[x]){
t[x]=y;
}
else{
t[y]=x;h[x]++;
}
}
int main()
{
ifstream fin("apm.in");
ofstream fout("apm.out");
int n,m;fin>>n>>m;
for(int i=1;i<=m;i++){
fin>>v[i].x>>v[i].y>>v[i].cost;
v[i].val=0;
}sort(v+1,v+m+1,cmp);int cnt=0,sum=0;
for(int i=1;i<=n;i++){
h[i]=1;t[i]=i;
}int nr1,nr2;
for(int i=1;i<=m;i++){
nr1=find1(v[i].x);
nr2=find1(v[i].y);
if(nr1!=nr2){
union1(nr1,nr2);sum+=v[i].cost;v[i].val=1;cnt++;
}
}
fout<<sum<<'\n'<<cnt<<'\n';
for(int i=1;i<=m;i++){
if(v[i].val==1){
fout<<v[i].x<<" "<<v[i].y<<'\n';
}
}
return 0;
}