Pagini recente » Cod sursa (job #1190683) | Cod sursa (job #938199) | Cod sursa (job #2054409) | Cod sursa (job #1472066) | Cod sursa (job #3344222)
#include <fstream>
#define NMAX 200001
#define MMAX 400001
#include <vector>
#include <queue>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
struct muchie
{
int x,y,c;
friend bool operator < (muchie a,muchie b);
};
bool operator < (muchie a,muchie b)
{
return a.c>b.c;
}
priority_queue<muchie> H;
int n,m,cmin;
int tata[NMAX],rg[NMAX];
muchie apm[MMAX];
void kruskal();
int gaseste(int x);
void uneste(int x,int y);
int main()
{
int i;
muchie aux;
fin>>n>>m;
for(i=1;i<=m;i++)
{
fin>>aux.x>>aux.y>>aux.c;
H.push(aux);
}
kruskal();
fout<<cmin<<'\n'<<n-1<<'\n';
for(i=1;i<n;i++) fout<<apm[i].x<<' '<<apm[i].y<<'\n';
return 0;
}
void kruskal()
{
int nrsel=0,rx,ry;
muchie aux;
while(nrsel<n-1)
{
aux=H.top(); H.pop();
rx=gaseste(aux.x); ry=gaseste(aux.y);
if(rx!=ry)
{
cmin+=aux.c;
apm[++nrsel]=aux;
uneste(rx,ry);
}
}
}
int gaseste(int x)
{
int rx,y;
for(rx=x;tata[rx];rx=tata[rx]);
while(tata[x] && tata[x]!=rx)
{
y=tata[x];
tata[x]=rx;
x=y;
}
return rx;
}
void uneste(int x,int y)
{
if(rg[x]>rg[y]) tata[y]=x;
else if(rg[y]>rg[x]) tata[x]=y;
else
{
tata[y]=x;
rg[x]++;
}
}