Pagini recente » Cod sursa (job #1444081) | Cod sursa (job #2390280) | Cod sursa (job #1410808) | Cod sursa (job #3157869) | Cod sursa (job #2000449)
#include <fstream>
#include <algorithm>
using namespace std;
ifstream fin("amp.in");
ofstream fout("amp.out");
const int nmax=200000;
int t[nmax+3],h[nmax+3];
struct muchie{int x,y,cost;};
muchie v[nmax+3];
int findset(int x)
{
while(t[x]!=x)
x=t[x];
return x;
}
void unionset(int x, int y)
{
if(h[x]==h[y])
{
h[x]++;
t[y]=x;
}
else if(h[x]>h[y]) t[y]=x;
else t[x]=y;
}
bool cmp(muchie a, muchie b)
{
return a.cost<b.cost;
}
muchie sol[nmax];
int main()
{
int n,m,cmin=0,i,nr=0,a,b;
fin>>n>>m;
for(i=1;i<=m;i++)
{
fin>>v[i].x>>v[i].y>>v[i].cost;
}
sort(v+1,v+m+1,cmp);
for(i=1;i<=n;i++)
{
t[i]=i;
h[i]=1;
}
for(i=1;i<=m&&nr<=n-1;i++)
{
a=findset(v[i].x);
b=findset(v[i].y);
if(a!=b)
{
unionset(a,b);
cmin+=v[i].cost;
nr++;
sol[nr].x=v[i].x;
sol[nr].y=v[i].y;
}
}
fout<<cmin<<"\n"<<n-1<<"\n";
for(i=1;i<=n-1;i++)
fout<<sol[i].x<<" "<<sol[i].y<<"\n";
return 0;
}