Cod sursa(job #1686959)

Utilizator TibixbAndrei Tiberiu Tibixb Data 12 aprilie 2016 15:52:31
Problema Arbore partial de cost minim Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 2 kb
#include<fstream>
#include<vector>
#include<cstring>
using namespace std;
vector<pair<int, int> > L[200005];
bool u[200005];
int t[200005], n, m, i, x, y, z, D[200005], h[200005], p[200005], nrh, nod, cost, vecin, s, p1, apm;
void remove_root()
{
    h[1]=h[nrh];
    p[h[1]]=1;
    nrh--;
    p1=1;
    s=2;
    while(s<=nrh)
    {
        if(s+1<=nrh && D[h[s]]<D[h[p1]])
            s++;
        if(D[h[s]]<D[h[p1]])
        {
            swap(h[s], h[p1]);
            p[h[s]]=s;
            p[h[p1]]=p1;
            p1=s;
            s*=2;
        }else
        {
            break;
        }
    }
}
void prim()
{
    while(nrh!=0)
    {
        nod=h[1];
        apm+=D[nod];
        u[nod]=1;
        remove_root();
        for(i=0; i<L[nod].size(); i++)
        {
            vecin=L[nod][i].first;
            cost=L[nod][i].second;
            if(D[vecin]>cost && u[vecin]==0)
            {
                D[vecin]=cost;
                t[vecin]=nod;
                if(p[vecin]==0)
                {
                    h[++nrh]=vecin;
                    p[vecin]=nrh;
                    s=p[vecin];
                    p1=s/2;
                }else
                {
                    s=p[vecin];
                    p1=s/2;
                }
                while(p1!=0 && D[h[s]]<D[h[p1]])
                {
                    swap(h[s], h[p1]);
                    p[h[s]]=s;
                    p[h[p1]]=p1;
                    s=p1;
                    p1/=2;
                }
            }
        }
    }
}
ifstream in("apm.in");
ofstream out("apm.out");
int main()
{
    in>>n>>m;
    for(i=1; i<=m; i++)
    {
        in>>x>>y>>z;
        L[x].push_back(make_pair(y, z));
        L[y].push_back(make_pair(x, z));
    }
    memset(D, 127, sizeof(D));
    D[1]=0;
    h[++nrh]=1;
    p[1]=1;
    prim();
    out<<apm<<"\n";
    out<<n-1<<"\n";
    for(i=2; i<=n; i++)
    {
        out<<t[i]<<" "<<i<<"\n";
    }
    return 0;
}