Cod sursa(job #2553933)

Utilizator rares9991Matisan Rares-Stefan rares9991 Data 22 februarie 2020 13:20:41
Problema Arbore partial de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.72 kb
#include <fstream>
#define INF 1e9
using namespace std;

ifstream in ("heapuri.in");
ofstream out ("heapuri.out");

//algortimul lui Prim

const int N=200001;
const int M=2*N;

int lst[N], cst[2*M], urm[2*M], vf[2*M], d[N], nr, nh, cost, pred[N], n, m, nrm, h[N], poz[N];
bool selectat[N];

void adauga_muchie(int x, int y, int c)
{
    vf[++nr]=y;
    cst[nr]=c;
    urm[nr]=lst[x];
    lst[x]=nr;
}

void schimb(int p, int q)
{
    swap(h[p], h[q]);
    poz[h[p]]=p;
    poz[h[q]]=q;
}

void urca(int p)
{
    while(p>1 and d[h[p]]<d[h[p/2]])
    {
        schimb(p,p/2);
        p/=2;
    }
}

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

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

void adauga(int x)
{
    h[++nh]=x;
    poz[x]=nh;
    urca(nh);
}

void prim()
{
    int x,y,c;
    for(int i=2; i<=n; i++)
    {
        d[i]=INF;
        adauga(i);
    }
    d[1]=0;
    adauga(1);
    while(nh>0)
    {
        x=h[1];
        sterge(1);
        selectat[x]=true;
        cost+=d[x];
        for(int p=lst[x]; p!=0; p=urm[p])
        {
            y=vf[p];
            c=cst[p];
            if(c<d[y] and !selectat[y])
            {
                d[y]=c;
                pred[y]=x;
                urca(poz[y]);
            }
        }
    }
}

int main()
{
    in>>n>>m;
    for(int i=1; i<=m; i++)
    {
        int x, y, c;
        in>>x>>y>>c;
        adauga_muchie(x,y,c);
        adauga_muchie(y,x,c);
    }
    prim();
    out<<cost<<"\n"<<n-1<<"\n";
    for(int i=2; i<=n; i++)
    out<<i<<" "<<pred[i]<<"\n";
    return 0;
}