Pagini recente » Statistici Jung Hoseok (jung_hoseok) | Cod sursa (job #442046) | Istoria paginii utilizator/rares_liviu | Cod sursa (job #1781844) | Cod sursa (job #604448)
Cod sursa(job #604448)
#include <iostream>
#include <vector>
#define NMax 200005
#define Inf 2000000000
#define v first
#define c second
using namespace std;
vector < pair <int, int> > G[NMax];
int N, Heap[NMax], NHeap, Prim[NMax], Poz[NMax], Father[NMax], CostAPM;
void Read ()
{
freopen ("apm.in", "r", stdin);
int M;
scanf ("%d %d", &N, &M);
for (; M>0; --M)
{
int X, Y, Z;
scanf ("%d %d %d", &X, &Y, &Z);
G[X].push_back (make_pair (Y, Z));
G[Y].push_back (make_pair (X, Z));
}
}
void Print ()
{
freopen ("apm.out", "w", stdout);
printf ("%d\n%d\n", CostAPM, N-1);
for (int i=2; i<=N; ++i)
{
printf ("%d %d\n", Father[i], i);
}
}
inline void Swap (int X, int Y)
{
int Aux;
Aux=Poz[Heap[X]];
Poz[Heap[X]]=Poz[Heap[Y]];
Poz[Heap[Y]]=Aux;
Aux=Heap[X];
Heap[X]=Heap[Y];
Heap[Y]=Aux;
}
void Percolate (int X)
{
int F=(X>>1);
if (F>0 and Prim[Heap[X]]<Prim[Heap[F]])
{
Swap (X, F);
Percolate (F);
}
}
void Sift (int X)
{
int Son=(X<<1);
if (Son+1<=NHeap and Prim[Heap[Son+1]]<Prim[Heap[Son]])
{
++Son;
}
if (Son<=NHeap and Prim[Heap[Son]]<Prim[Heap[X]])
{
Swap (X, Son);
Sift (Son);
}
}
void Delete (int X)
{
Swap (X, NHeap);
Poz[Heap[NHeap]]=-1;
Heap[NHeap]=0;
--NHeap;
Sift (X);
}
void Initialize (int Start)
{
for (int i=1; i<=N; ++i)
{
Prim[i]=Inf;
Heap[i]=Poz[i]=i;
}
NHeap=N;
Prim[Start]=0;
Swap (1, Start);
}
void APM (int Start)
{
Initialize (Start);
while (NHeap>0)
{
int X=Heap[1];
Delete (1);
for (unsigned i=0; i<G[X].size (); ++i)
{
int V=G[X][i].v;
int C=G[X][i].c;
if (Poz[V]!=-1 and C<Prim[V])
{
Prim[V]=C;
Father[V]=X;
Percolate (Poz[V]);
}
}
}
}
int main()
{
Read ();
APM (1);
for (int i=1; i<=N; ++i)
{
CostAPM+=Prim[i];
}
Print ();
return 0;
}