Pagini recente » Cod sursa (job #2393376) | Cod sursa (job #184576) | Cod sursa (job #222066) | Cod sursa (job #481714) | Cod sursa (job #604485)
Cod sursa(job #604485)
#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, APM[NMax], Father[NMax], NHeap, Heap[NMax], Poz[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 APM[Heap[X]]<APM[Heap[F]])
{
Swap (X, F);
Percolate (F);
}
}
void Sift (int X)
{
int Son=(X<<1);
if (Son+1<=NHeap and APM[Heap[Son+1]]<APM[Heap[Son]])
{
++Son;
}
if (Son<=NHeap and APM[Heap[Son]]<APM[Heap[X]])
{
Swap (X, Son);
Sift (Son);
}
}
void Delete (int X)
{
Swap (X, NHeap);
Poz[Heap[NHeap]]=0;
Heap[NHeap]=0;
--NHeap;
Sift (X);
}
void Initialize (int Start)
{
NHeap=N;
for (int i=1; i<=N; ++i)
{
APM[i]=Inf;
Heap[i]=Poz[i]=i;
}
APM[Start]=0;
Swap (1, Start);
}
void Prim (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]!=0 and C<APM[V])
{
APM[V]=C;
Father[V]=X;
Percolate (Poz[V]);
}
}
}
}
int main()
{
Read ();
Prim (1);
for (int i=1; i<=N; ++i)
{
CostAPM+=APM[i];
}
Print ();
return 0;
}