Cod sursa(job #649050)

Utilizator rootsroots1 roots Data 15 decembrie 2011 09:44:04
Problema Arbore partial de cost minim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.54 kb
#include <fstream>
#include <cstring>

#define gSize 200001
#define heapSize 200001
#define posSize 200001
#define TSize 200001
#define dSize 200001
#define useSize 200001

#define INF 0x7fffffff

using namespace std;

ifstream in;
ofstream out;

struct graf
{
    int nod,cost;
    graf *link;
}*g[gSize];

int heap[heapSize];
int pos[posSize];
int T[TSize];
int d[dSize];
int use[useSize];

int N,cnt=0;

inline void add_edge(int x,int y,int c)
{
    graf *p=new graf;
    p->nod=y;
    p->cost=c;
    p->link=g[x];
    g[x]=p;
}

inline void HeapUp(int nod)
{
    int aux=heap[nod];

    for(;nod>1&&d[heap[nod>>1]]>d[aux];nod>>=1)
    {
        heap[nod]=heap[nod>>1];
        pos[heap[nod]]=nod;
    }

    heap[nod]=aux;
    pos[aux]=nod;
}

inline void HeapDown()
{
    int nod=1,L,R,aux=heap[1];

    while(1)
    {
        L=nod<<1;
        R=L+1;

        if(R<=heap[0]&&d[heap[L]]>d[heap[R]]&&d[aux]>d[heap[R]])
        {
            heap[nod]=heap[R];
            pos[heap[nod]]=nod;
            nod=R;
        }
        else
        if(L<=heap[0]&&d[heap[L]]<d[aux])
        {
            heap[nod]=heap[L];
            pos[heap[nod]]=nod;
            nod=L;
        }
        else
        {
            heap[nod]=aux;
            pos[aux]=nod;
            return;
        }
    }
}

inline void PopHeap()
{
    pos[heap[1]]=0;
    heap[1]=heap[heap[0]];
    heap[heap[0]]=0;
    pos[heap[1]]=1;
    --heap[0];

    HeapDown();
}

inline void PushHeap(int nod)
{
    ++heap[0];
    heap[heap[0]]=nod;
    pos[nod]=heap[0];
}

inline void Prim()
{
    heap[0]=1;
    heap[1]=1;
    pos[1]=1;
    d[1]=0;
    for(int i=2;i<=N;++i) d[i]=INF;
    memset(use,0,sizeof(use));

    for(int nod;heap[0];)
    {
        nod=heap[1];
        use[nod]=1;
        PopHeap();

        for(graf *p=g[nod];p;p=p->link)
            if(!use[p->nod]&&d[p->nod]>p->cost)
            {
                if(d[p->nod]==INF) PushHeap(p->nod);
                HeapUp(pos[p->nod]);
                d[p->nod]=p->cost;
                T[p->nod]=nod;
            }
    }
}

int main()
{
    int M,x,y,c;

    in.open("apm.in");

    in>>N>>M;
    for(;M--;)
    {
        in>>x>>y>>c;
        add_edge(x,y,c);
        add_edge(y,x,c);
    }

    in.close();

    Prim();

    out.open("apm.out");

    for(int i=2;i<=N;++i) cnt+=d[i];
    out<<cnt<<'\n'<<N-1<<'\n';
    for(int i=2;i<=N;++i)
        out<<T[i]<<' '<<i<<'\n';

    out.close();

    return 0;
}