Pagini recente » Cod sursa (job #960717) | Cod sursa (job #2581760) | Cod sursa (job #1999002) | Cod sursa (job #2562959) | Cod sursa (job #1366445)
#include<fstream>
#include<vector>
using namespace std;
ifstream in("apm.in");
ofstream out("apm.out");
#define Nmax 200005
#define INF ((1<<31)-1)
struct muchie
{
int y, cost;
};
vector < muchie > a[Nmax];
int d[Nmax];
int n, m;
int poz[Nmax], h[Nmax];
int nh;
int ok[Nmax], pred[Nmax];
void schimba(int i1, int i2)
{
int aux = h[i1];
h[i1] = h[i2];
h[i2] = aux;
poz[h[i1]] = i1;
poz[h[i2]] = i2;
}
void urca(int i)
{
while( i > 1 && d[h[ i ]] < d[h[i / 2]])
{
schimba(i, i/2);
i/=2;
}
}
void coboara(int i)
{
int bun = i, fs = i*2, fd = i*2+1;
if(fs <= nh && d[h[ fs ]] < d[h[ bun ]])
bun=fs;
if(fd <= nh && d[h[ fd ]] < d[h[ bun ]])
bun=fd;
if(bun != i)
{
schimba(bun, i);
coboara(bun);
}
}
void adauga(int x)
{
h[++nh] = x;
poz[x] = nh;
urca(nh);
}
void sterge(int i)
{
schimba(nh, i);
nh--;
coboara(i);
urca(i);
}
void apm(int x)
{
nh = 0;
for(int i=1; i<=n; i++)
d[i] = INF;
d[x] = 0;
adauga(x);
while(nh != 0)
{
x = h[1];
ok[x] = 1;
sterge(1);
for(size_t i=0; i<a[x].size(); ++i)
{
int y = a[x][i].y;
int cost = a[x][i].cost;
if( cost < d[y] && !ok[y])
{
d[y] = cost;
pred[y] = x;
if(poz[y] == 0)
adauga(y);
else
urca(poz[y]);
}
}
}
}
void citire()
{
int x, y, cost;
in >> n >> m;
for(int i=1; i<=m; i++)
{
in >> x >> y >> cost;
a[x].push_back((muchie) {y, cost});
a[y].push_back((muchie) {x, cost});
}
}
void afisare()
{
int s=0;
for(int i=1; i<=n ;i++)
s+= d[i];
out << s << '\n' << n-1 << '\n';
for(int i=2; i<=n ;i++)
out << i << ' ' << pred[i] <<'\n';
}
int main ()
{
citire();
apm(1);
afisare();
return 0;
}