Pagini recente » Cod sursa (job #881452) | Cod sursa (job #3041821) | Cod sursa (job #2775295) | Cod sursa (job #2364373) | Cod sursa (job #1829809)
#include <fstream>
#include <algorithm>
#define nmax 200001
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
struct muchie
{int x,y;
float c;
};
muchie a[nmax*2],sol[nmax];
int t[nmax],h[nmax];
int n,m,nrmsel;
float cost;
void Citire()
{int i;
fin>>n>>m;
for(i=1;i<=m;i++)
fin>>a[i].x>>a[i].y>>a[i].c;
}
int Find(int x)
{while(t[x]!=0) x=t[x];
return x;
}
void Union(int x,int y)
{if(h[x]>h[y]) t[y]=x;
else {t[x]=y;
if(h[x]==h[y]) h[y]++;
}
}
void Kruskal()
{int i,v1,v2,x1,x2;
for(i=1;i<=n;i++)
h[i]=1;
nrmsel=0; i=1;
while(nrmsel<n-1)
{v1=a[i].x; v2=a[i].y;
x1=Find(v1); x2=Find(v2);
if(x1!=x2)
{nrmsel++;
sol[nrmsel].x=v2;
sol[nrmsel].y=v1;
cost=cost+a[i].c;
Union(x1,x2);
}
i++;
}
}
void Afisare()
{int i;
fout<<cost<<"\n"<<nrmsel<<"\n";
for(i=1;i<=nrmsel;i++)
fout<<sol[i].x<<" "<<sol[i].y<<"\n";
}
inline int Comp(muchie x1,muchie x2)
{if(x1.c<x2.c) return 1;
return 0;
}
int main()
{
Citire();
sort(a+1,a+m+1,Comp);
Kruskal();
Afisare();
fin.close();
fout.close();
return 0;
}