Cod sursa(job #1506951)

Utilizator badea_adi1999Badea Adrian Catalin badea_adi1999 Data 21 octombrie 2015 09:15:12
Problema Arbore partial de cost minim Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.94 kb
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
#define nmax 200005
#define inf 2000000000
using namespace std;
int n,m,k;
int heap[nmax];
int poz[nmax],ans;
int d[nmax],l[nmax];


vector <pair <int, int > > v[nmax];

vector <pair <int,int > > sol;

void heapup(int nod)
{
    int po=poz[nod];
    while (po>1&&d[heap[po]]<d[heap[po/2]]) {

        swap(poz[heap[po]],poz[heap[po/2]]);
        swap(heap[po],heap[po/2]);
        po/=2;
    }
}
void heapdown(int nod)
{
    int son=0;
    if (nod*2<=k&&d[heap[nod*2]]<d[heap[nod]])
        son=nod*2;
    if (nod*2+1<=k&&d[heap[nod*2+1]]<d[heap[nod]]&&d[heap[nod*2+1]]<d[heap[nod*2]])
        son=nod*2+1;
    if (son==0)
        return;
    swap(poz[heap[nod]],poz[heap[son]]);
    swap(heap[nod],heap[son]);
    heapdown(son);

}
void extractheap()
{
    int son;
    swap(poz[heap[1]],poz[heap[k]]);
    swap(heap[1],heap[k]);
    heap[k]=poz[heap[k]]=0;
    k--;
    heapdown(1);

}
int main()
{
    freopen("apm.in","r",stdin);
    freopen("apm.out","w",stdout);
    scanf("%d %d",&n,&m);
    int i,j;
    int x,y,z;
    for (i=1;i<=m;i++) {
        scanf("%d %d %d",&x,&y,&z);
        v[x].push_back(make_pair(y,z));
        v[y].push_back(make_pair(x,z));
    }
    poz[1]=1;
    heap[1]=1;
    for (i=2;i<=n;i++) {
        d[i]=inf;
        heap[i]=i;
        poz[i]=i;
    }
    for (k=n;k;) {
        i=heap[1];
        ans+=d[i];
        if (l[i])
            sol.push_back(make_pair(l[i],i));
        d[i]=-inf;
        extractheap();
        for (j=0;j<v[i].size();j++) {
            y=v[i][j].first;
            z=v[i][j].second;
            if (z<d[y]) {
                d[y]=z;
                heapup(y);
                l[y]=i;
            }
        }
    }
    printf("%d\n%d\n",ans,sol.size());
    for (i=0;i<sol.size();i++)
        printf("%d %d\n",sol[i].first,sol[i].second);

    return 0;
}