Cod sursa(job #1500166)

Utilizator serbanSlincu Serban serban Data 11 octombrie 2015 16:16:36
Problema Arbore partial de cost minim Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 2.41 kb
#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];

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;
    if(ls <= l && c[h[ls]] < c[h[poz]]) {
        if(rs  <= l && c[h[ls]] > c[h[rs]]) {
            swith(h[rs], h[poz]);
            swith(pz[h[rs]], pz[h[poz]]);
            poz = rs;
        }
        else {
            swith(h[ls], h[poz]);
            swith(pz[h[ls]], pz[h[poz]]);
            poz = ls;
        }
        cobor(poz);
    }
    else if(rs <= l && c[h[rs]] < c[h[poz]]) {
        swith(h[rs], h[poz]);
        swith(pz[h[rs]], pz[h[poz]]);
        poz = rs;
        cobor(poz);
    }
}

void urc(int poz) {
    int tata = poz / 2;
    if(tata > 0 && c[h[tata]] > c[h[poz]]) {
        swith(h[tata], h[poz]);
        swith(pz[h[tata]], pz[h[poz]]);
        poz = tata;
        urc(poz);
    }
}

void heap(int x) {
    l ++;
    h[l] = x;
    pz[x] = l;
    urc(pz[h[l]]);
}

int first() {
    int ret = h[1];
    h[1] = h[l];
    l --;

    swith(pz[ret], pz[h[1]]);
    cobor(1);
    return ret;
}

int main()
{
    ifstream f("apm.in");
    ofstream g("apm.out");

    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;
    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;
}