Cod sursa(job #1754289)

Utilizator andreix2cAndrei Cosmin andreix2c Data 7 septembrie 2016 20:41:57
Problema Arbore partial de cost minim Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 2.05 kb
#include <fstream>
#include <vector>
#include <limits>
using namespace std;
ifstream f("apm.in");
ofstream g("apm.out");
struct nod
{
    int value,cost;
    nod* next;
    nod(int value,int cost)
    {
        this->value=value;
        this->cost=cost;
        this->next=NULL;
    };
    nod(int value,int cost,nod*next)
    {
        this->value=value;
        this->cost=cost;
        this->next=next;
    };
}__attribute__((packed));
int n,m,cost,muchii,x,y,c,*viz,*cmin,*p,start=1,vfmin,MIN,MAX=numeric_limits<int>::max();
nod *aux;
void add(nod*&N,int value,int cost)
{
    if(N)
    {
        aux=new nod(value,cost,N);
        N=aux;
    }
    else N=new nod(value,cost);
}
int main()
{
    f>>n>>m;
    muchii=n-1;
    vector<nod*>N(n+1);
    viz=new int[n+1] {0};
    cmin=new int[n+1] {0};
    p=new int[n+1] {0};
    for(int i=1; i<=m; i++)
    {
        f>>x>>y>>c;
        add(N[x],y,c);
        add(N[y],x,c);
    }
    viz[start]=1;
    for(int i=1; i<=n; i++){
        cmin[i]=MAX;
        p[i]=start;
    }
    for(nod*p=N[start]; p!=NULL; p=p->next)
        cmin[p->value]=p->cost;
    while(muchii)
    {
        MIN=MAX;
        for(int i=1; i<=n; i++)
            if(!viz[i]&&cmin[i]<MIN)
            {
                vfmin=i;
                MIN=cmin[i];
            }
        viz[vfmin]=1;
        for(nod*p1=N[vfmin]; p1!=NULL; p1=p1->next)
            if(!viz[p1->value]&&p1->cost<cmin[p1->value])
            {
                p[p1->value]=vfmin;
                cmin[p1->value]=p1->cost;
            }
        muchii--;
    }
    muchii=n-1;
    for(int i=1; i<=n; i++)
    {
        if(i!=start)
        {
            for(nod*p1=N[i]; p1!=NULL; p1=p1->next)
                if(p1->value==p[i])
                {
                    cost+=p1->cost;
                    break;
                }
        }
    }
    g<<cost<<'\n'<<muchii<<'\n';
    for(int i=1; i<=n; i++)
    {
        if(i!=start)
        {
            g<<i<<" "<<p[i]<<'\n';
        }
    }
    return 0;
}