Cod sursa(job #373993)

Utilizator cristikIvan Cristian cristik Data 15 decembrie 2009 17:29:51
Problema Arbore partial de cost minim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.71 kb
#include <stdio.h>
#define max 100010
#define inf 10000
struct lista
{
    int nod,cost;
    lista *next;
};
lista *g[max],*p;
int n,m,j,d[max],t[max],h[max],poz[max],min,lg,i,c,cost,k,nr;
void swap(int i,int j)
{
    int t=h[i]; h[i]=h[j]; h[j]=t;
}
void push(int i,int j,int c)
{
    lista *p=new lista;
    p->cost=c;
    p->nod=j;
    p->next=g[i];
    g[i]=p;
}
void upheap(int x)
{
    while(x/2 && d[h[x]]<d[h[x/2]])
    {
        swap(x,x/2);
        poz[h[x]]=x;
        poz[h[x/2]]=x/2;
        x/=2;
    }
}
void downheap(int x)
{
    int y=0;
    while(x!=y)
    {
        y=x;
        if(y*2<=lg && d[h[x]]>d[h[y*2]]) x=y*2;
        if(y*2+1<=lg && d[h[x]]>d[h[y*2+1]]) x=y*2+1;
        swap(x,y);
        poz[h[x]]=x;
        poz[h[y]]=y;
    }
}
int main()
{
    freopen("apm.in","r",stdin);
    freopen("apm.out","w",stdout);
    scanf("%d%d",&n,&m);
    for(i=1; i<=n; i++) d[i]=inf,poz[i]=-1,t[i]=1;  d[1]=0;
    for(k=1; k<=m; k++)
    {
        scanf("%d%d%d",&i,&j,&c);
        push(i,j,c); push(j,i,c);
    }

    poz[1]=1;

    h[++lg]=1;

    while(lg)
    {

        min=h[1]; cost+=d[min]; nr++;
        swap(1,lg);
        poz[h[1]]=1;
        lg--;
        downheap(1);
        for(p=g[min]; p!=NULL; p=p->next)
         if(d[p->nod]>p->cost)
         {
             d[p->nod]=p->cost;
             t[p->nod]=min;
             if(poz[p->nod]!=-1) upheap(poz[p->nod]);
             else
             {
                 h[++lg]=p->nod;
                 poz[h[lg]]=lg;
                 upheap(lg);
             }
         }
    }
    printf("%d\n%d\n",cost,nr-1);
    for(i=2; i<=n; i++)
       printf("%d %d\n",t[i],i);
    return 0;
}