Pagini recente » Cod sursa (job #769877) | Cod sursa (job #1715668) | Cod sursa (job #2428371) | Cod sursa (job #2944329) | Cod sursa (job #2837522)
#include <fstream>
#include <queue>
#define NMAX 200001
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
struct muchie
{
int x, y;
int cost;
friend bool operator >(const muchie&, const muchie&);
};
bool operator >(const muchie& m1, const muchie& m2)
{
return m1.cost>m2.cost;
}
priority_queue<muchie, vector<muchie>, greater<muchie> > H;
vector<muchie> sol;
int tata[NMAX];
int h[NMAX];
int n;
double costmin;
void citire();
void afisare();
void Union(int x, int y)
{
if (h[x]>h[y])
tata[y]=x;
else
{
if (h[x]==h[y]) h[y]++;
tata[x]=y;
}
}
int Find(int x)
{
int rad=x, y, t;
while (tata[rad])
rad=tata[rad];
y=x;
while (y!=rad)
{
t=tata[y];
tata[y]=rad;
y=t;
}
return rad;
}
int main()
{
int c1, c2;
muchie m;
citire();
while (sol.size()<n-1)
{
m=H.top(); H.pop();
c1=Find(m.x); c2=Find(m.y);
if (c1!=c2)
{
costmin+=m.cost; sol.push_back(m);
Union(c1, c2);
}
}
afisare();
return 0;
}
void citire()
{
muchie m;
int i, nrm;
fin>>n>>nrm;
for (i=0; i<nrm; i++) {fin>>m.x>>m.y>>m.cost; H.push(m);}
}
void afisare()
{
fout<<costmin<<'\n';
for (int i=0; i<n-1; i++) fout<<sol[i].x<<" "<<sol[i].y<<'\n';
}