Pagini recente » Rating Traian Simedru (sevenraian) | Cod sursa (job #2842010) | Cod sursa (job #2398072) | Cod sursa (job #1430642) | Cod sursa (job #1388111)
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
#define nmax 200002
int n,i;
pair <int,int> sol[nmax];
struct muchie {
int x,y,c;
} v[2*nmax];
int tata[nmax],m,k,cost;
int indvalmin (int i, int n)
{
if (2*i+1<=n)
if(v[2*i].c<v[2*i+1].c)
return 2*i;
else
return 2*i+1;
else
return 2*i;
}
void combinare (int i, int n)
{
int ind;
muchie aux;
if (i<=n/2)
{
ind=indvalmin(i,n);
if (v[i].c>v[ind].c)
{
aux=v[i];
v[i]=v[ind];
v[ind]=aux;
combinare (ind,n);
}
}
}
void minheap ()
{
for (i=n/2;i>=1;i--)
combinare(i,n);
}
int radacina(int nod) {
if (tata[nod]==0)
return nod;
else {
tata[nod]=radacina(tata[nod]);
return tata[nod];
}
}
void citire ()
{
ifstream f ("apm.in");
f>>n;
while (f>>v[i].x>>v[i].y>>v[i].c) i++;
m=i;
f.close ();
}
void solve() {
int i,tx,ty;
for (i=1; i<=m; i++)
{
tx=radacina(v[i].x);
ty=radacina(v[i].y);
if (tx!=ty) {
tata[tx]=ty;
k++;
sol[k].first=v[i].x;
sol[k].second=v[i].y;
cost+=v[i].c;
}
}
}
int main()
{
citire ();
minheap ();
ofstream g ("apm.out");
solve();
g<<cost<<"\n"<<n-1<<"\n";
for (int i=1; i<=k; i++)
g<<sol[i].first<<" "<<sol[i].second<<"\n";
g.close();
return 0;
}