Pagini recente » Cod sursa (job #2059937) | Cod sursa (job #318950) | Cod sursa (job #916645) | Cod sursa (job #2765891) | Cod sursa (job #2857390)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
const int MAX = 200005, INF = (1 << 30);
int n, m;
int costNod[MAX], tata[MAX], costTotal = 0;
bool inArbore[MAX];
struct Compara
{
bool operator() (pair < int, int > x, pair < int, int > y)
{
return (x.second > y.second);
}
};
priority_queue < pair < int, int >, vector < pair < int, int > >, Compara > heap;
queue < pair < int, int > > drum[MAX];
void Citire()
{
fin >> n >> m;
for (int i = 1; i <= m; i++)
{
int x, y, cost;
fin >> x >> y >> cost;
drum[x].push(make_pair(y, cost));
drum[y].push(make_pair(x, cost));
}
}
void Prim()
{
for (int i = 2; i <= n; i++)
{
costNod[i] = INF;
}
heap.push(make_pair(1, 0));
while(!heap.empty())
{
int nodActual = heap.top().first;
int costActual = heap.top().second;
heap.pop();
/*cout << nodActual << ' ' << costNod[nodActual] << '\n';
for(int i = 1; i <= n; i++)
{
cout << i << ' ' << costNod[i] << '\n';
}
cout << '\n';*/
if (!inArbore[nodActual])
{
inArbore[nodActual] = true;
while (!drum[nodActual].empty())
{
int nodUrmator = drum[nodActual].front().first;
int cost = drum[nodActual].front().second;
drum[nodActual].pop();
if (!inArbore[nodUrmator])
{
if (cost < costNod[nodUrmator])
{
heap.push(make_pair(nodUrmator, cost));
costNod[nodUrmator] = cost;
tata[nodUrmator] = nodActual;
}
}
}
}
}
}
void Afisare()
{
for (int i = 2; i <= n; i++)
{
costTotal += costNod[i];
}
fout << costTotal << '\n';
fout << n - 1 << '\n';
for (int i = 2; i <= n; i++)
{
fout << i << ' ' << tata[i] << '\n';
}
}
int main()
{
Citire();
Prim();
Afisare();
/*costNod[1] = 1;
costNod[2] = -5;
costNod[3] =4;
costNod[4] =8;costNod[5] =-34;
costNod[6] =5;costNod[7] =0;costNod[8] =-5;costNod[9] =6;
costNod[10] =-17;
for (int i = 1; i <= 10; i++)
{
heap.push(i);
}
while (!heap.empty())
{
cout << heap.top() << ' ' << costNod[heap.top()] << '\n';
heap.pop();
}*/
return 0;
}