Cod sursa(job #1500170)

Utilizator serbanSlincu Serban serban Data 11 octombrie 2015 16:24:19
Problema Arbore partial de cost minim Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 2.57 kb
#include <bits/stdc++.h>
#define inf 2147483647

using namespace std;

struct node{
    node *next;
    int first;
    int second;
};
node *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(node *p = L[x]; p; p = p->next) {
        int where = p->first;
        int much = p->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;
}

void add(node *&start, int nod, int cost) {
    node *one = new node;
    one->next = start;
    one->first = nod;
    one->second = cost;
    start = one;
}

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;
        add(L[X], Y, C);
        add(L[Y], 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(node *p = L[x]; p; p = p->next) {
            if(pz[p->first] <= l)
                urc(pz[p->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;
}