Pagini recente » Cod sursa (job #1186429) | Cod sursa (job #1998162) | Cod sursa (job #2115566) | Cod sursa (job #1465481) | Cod sursa (job #1255351)
// ok - infoarena
#include <stdio.h>
#include <queue>
#include <bitset>
using namespace std;
const int Nmax = 200001, Inf = 1 << 30;
#define x first
#define y second
struct Edge {
int node, cost;
const bool operator < (const Edge &e) const
{
return cost > e.cost;
}
};
vector<Edge> G[Nmax + 1];
vector<pair<int, int>> apm;
priority_queue<Edge> Q;
vector<int> key, t; // cheile, predecesorii
int n;
long long cost_apm;
bitset<Nmax + 1> v;
void Prim (int k)
{
key = vector<int>(n + 1, Inf);
t = vector<int>(n + 1);
int x, w; // vecinul lui k si costul muchiei
key[k] = 0;
Q.push({k, 0});
while (!Q.empty() )
{
k = Q.top().node;
v[k] = 1; // cost minim final pentru k (nu tebuie sa mai intre in coada)
for (const auto& e : G[k])
{
x = e.node;
if ( v[x] ) continue;
w = e.cost;
if( key[x] > w )
{
key[x] = w;
t[x] = k;
Q.push({x, key[x]});
}
}
apm.push_back({t[k], k}); // adaug in apm si sursa (k, cu t[k] = 0)
cost_apm += key[k]; // adaug si costul sursei k: 0
while (!Q.empty() && v[Q.top().node])
Q.pop();
}
}
int main()
{
freopen("apm.in","r",stdin);
freopen("apm.out","w",stdout);
int a, b, c, m;
scanf("%d%d", &n, &m);
for (int i = 1; i <= m; i++) // sar peste muchie [t[k], k]
{
scanf("%d%d%d", &a, &b, &c);
G[a].push_back({b, c});
G[b].push_back({a, c});
}
Prim(1);
printf("%lld\n", cost_apm);
printf("%d\n", (int)apm.size() - 1);
for (size_t i = 1; i < apm.size(); ++i)
printf("%d %d\n", apm[i].x, apm[i].y);
return 0;
}