Cod sursa(job #1650437)

Utilizator TibixbAndrei Tiberiu Tibixb Data 11 martie 2016 18:21:08
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.29 kb
#include<fstream>
#include<vector>
#include<cstring>
using namespace std;
vector<pair<int, int> > L[200005];
bool u[200005];
int n, m, i, x, y, z, h[200005], p[200005], D[200005], nod, nodd, p1, s, vecin, cost, apm, nrh, nrsol, t[200005];
                                                                                                                                                                                                int soll[200005];
void prim()
{
    while(nrh!=0)
    {
        nod=h[1];
        u[nod]=1;
        apm+=D[nod];
        soll[nrsol]=nod;
        nrsol++;
        h[1]=h[nrh];
        p[h[1]]=1;
        nrh--;
        p1=1;
        s=2;
        while(s<=nrh)
        {
            if(s+1<=nrh && D[h[s+1]]<D[h[s]])
                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;
            }
        }
        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)
                {
                    s=p[vecin];
                    p1=s/2;
                }else
                {
                    h[++nrh]=vecin;
                    p[vecin]=nrh;
                    s=nrh;
                    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));
    }
    h[++nrh]=1;
    p[1]=1;
    memset(D, 127, sizeof(D));
    D[1]=0;
    prim();
    out<<apm<<"\n"<<nrsol-1<<"\n";
    for(i=1; i<nrsol; i++)
        out<<t[soll[i]]<<" "<<soll[i]<<"\n";
    return 0;
}