Pagini recente » Cod sursa (job #2504187) | Cod sursa (job #1100585) | Cod sursa (job #1536857) | Cod sursa (job #1798061) | Cod sursa (job #1500221)
#include <bits/stdc++.h>
#define inf 2147483647
using namespace std;
vector< pair<int, int> > L[200005];
int c[200005];
int t[200005];
int h[200005], l;
int pz[200005];
ofstream g("apm.out");
void swith(int &a, int &b) {
int aux = a;
a = b;
b = aux;
}
void apm(int x) {
for(int i = 0; i < L[x].size(); i ++) {
int where = L[x][i].first;
int much = L[x][i].second;
if(c[where] > much)
c[where] = much, t[where] = x;
}
}
void cobor(int poz) {
int ls = poz * 2;
int rs = poz * 2 + 1;
while((rs <= l && c[h[rs]] < c[h[poz]]) || (ls <= l && c[h[ls]] < c[h[poz]])) {
if(rs <= l && c[h[rs]] < c[h[ls]]) {
swith(pz[h[rs]], pz[h[poz]]);
swith(h[rs], h[poz]);
poz = rs;
rs = poz * 2 + 1;
ls = poz * 2;
}
else{
swith(pz[h[ls]], pz[h[poz]]);
swith(h[ls], h[poz]);
poz = ls;
rs = poz * 2 + 1;
ls = poz * 2;
}
}
}
void urc(int poz) {
int tata = poz / 2;
while(tata > 0 && c[h[tata]] > c[h[poz]]) {
swith(h[tata], h[poz]);
swith(pz[h[tata]], pz[h[poz]]);
poz = tata;
tata /= 2;
}
}
void heap(int x) {
l ++;
h[l] = x;
pz[x] = l;
urc(l);
}
int first() {
int ret = h[1];
h[1] = h[l];
l --;
swith(pz[ret], pz[h[1]]);
cobor(1);
pz[ret] = l + 1;
return ret;
}
int main()
{
ifstream f("apm.in");
int n, m, X, Y, C;
f >> n >> m;
for(int i = 1; i <= m; i ++) {
f >> X >> Y >> C;
L[X].push_back(make_pair(Y, C));
L[Y].push_back(make_pair(X, C));
}
for(int i = 1; i <= n; i ++)
c[i] = inf;
h[0] = 0;
c[0] = inf;
c[1] = 0;
apm(1);
for(int i = 2; i <= n; i ++) {
heap(i);
}
int ans = 0;
vector<pair<int, int>> ret;
for(int i = 2; i <= n; i ++) {
int x = first();
apm(x);
ans += c[x];
ret.push_back(make_pair(x, t[x]));
for(int j = 0; j < L[x].size(); j ++) {
if(pz[L[x][j].first] <= l)
urc(pz[L[x][j].first]);
}
}
g << ans << "\n";
g << n - 1 << "\n";
for(int i = 0; i < ret.size(); i ++) {
g << ret[i].first << " " << ret[i].second << "\n";
}
return 0;
}