Cod sursa(job #2166790)

Utilizator RazvanatorHilea Razvan Razvanator Data 13 martie 2018 18:56:15
Problema Arbore partial de cost minim Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 2.04 kb
#include <fstream>
#include <vector>
#define MMAX 400005
#define INF 2000000000
#define NMAX 200005

using namespace std;

ifstream fin("apm.in");
ofstream fout("apm.out");

int n, m;
int x, y, cost;
vector < int > a[MMAX];
vector < int > c[MMAX];
bool viz[NMAX];
int h[NMAX];
int poz[NMAX];
int d[NMAX];
int nh;
int pred[NMAX];

void schimba (int p,int q)
{
    int aux;
    aux = h[p];
    h[p] = h[q];
    h[q] = aux;
    poz[h[p]] = p;
    poz[h[q]] = q;
}

void coboara(int p)
{
    int fs = 2*p,fd = 2*p+1,bun = p;
    if (fs <= nh && d[h[fs]] < d[h[bun]])
        bun = fs;
    if (fd <= nh && d[h[fd]] < d[h[bun]])
        bun = fd;
    if (bun != p)
    {
        schimba(p, bun);
        coboara(bun);
    }
}

void urca(int p)
{
    if (p == 1) return;
    if (p > 1 && d[h[p]] < d[h[p/2]])
        schimba(p, p/2);
        urca(p/2);
}

void sterge(int p)
{
    schimba(p, nh--);
    urca(p);
    coboara(p);
}

void prim(int x0)
{
    for (int i = 1; i <= n; i++) {
        d[i] = INF;
        h[i] = i;
        poz[i] = i;
    }
    d[x0] = 0;
    pred[x0] = 0;
    urca(poz[x0]);
    nh = n;
    while (nh > 0 && d[h[1]] != INF) {
        x = h[1];
        viz[x] = true;
        sterge(1);
        for (int i = 0; i < a[x].size(); i++) {
            y = a[x][i];
            cost = c[x][i];
            if (viz[y]) continue;
            if (cost < d[y]) {
                d[y] = cost;
                pred[y] = x;
                urca(poz[y]);
            }
        }
    }
}

int calcul()
{
    int suma = 0;
    for (int i = 1; i <= n; i++) {
        if (pred[i] != 0) suma += d[i];
    }
    return suma;
}

int main()
{
    fin>>n>>m;
    for (int i = 1; i <= m; i++) {
        fin>>x>>y>>cost;
        a[x].push_back(y);
        a[y].push_back(x);
        c[x].push_back(cost);
        c[y].push_back(cost);
    }
    prim(1);
    fout<<calcul()<<'\n';
    int qwe = 0;
    for (int i = 1; i <= n; i++) {
        if (pred[i] != 0) qwe++;
    }
    fout<<qwe<<'\n';
    for (int i = 1; i <= n; i++) {
        if (pred[i] != 0) fout<<pred[i]<<' '<<i<<'\n';
    }
}