Cod sursa(job #764231)

Utilizator ioanabIoana Bica ioanab Data 4 iulie 2012 15:02:16
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.91 kb
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;

ifstream in("apm.in");
ofstream out("apm.out");

struct nod
{
    int x,cost;

    nod(int _x, int _cost)
    {
        x=_x;
        cost=_cost;
    }
    nod()
    {

        x=0;
        cost=0;
    }

    bool operator <(const nod &X) const
    {
        return cost>X.cost;
    }
};

const int N=200006;
const int inf=0x3f3f3f3f;

bool use[N];
int dist[N],n,m,apm, pred[N];
vector <nod> v[N];
nod sol[N];

void dijkstra(int start)
{
    memset(use,0,sizeof(use));
    memset(dist,inf, sizeof(dist));
    int x,y,c;
    dist[start]=0;

    priority_queue <nod> h;
    h.push(nod(start,dist[start]));

    while(!h.empty())
    {
        x=h.top().x;

        if(use[x])
        {
            h.pop();
            continue;
        }

        use[x]=true;

        apm+=h.top().cost;
        h.pop();

        for(vector <nod> :: iterator it=v[x].begin(); it!=v[x].end(); it++)
        {
            y=it->x;
            c=it->cost;
            if(dist[y]>c &!use[y])
            {
                dist[y]=c;
                h.push(nod(y,c));
                pred[y]=x;
            }
        }
    }

}

int main()
{
    int x,y,c,nr,i;
    in>>n>>m;
    for(int i=1;i<=m;i++)
    {
        in>>x>>y>>c;
        v[x].push_back(nod(y,c));
        v[y].push_back(nod(x,c));
    }

    dijkstra(1);
    out<<apm<<"\n";
    nr=0;
    for(i=n;i>=1;i--)
    {
        if(pred[i])
        {
            x=i;
            while(pred[x])
            {
                nr++;
                sol[nr].x=pred[x];
                sol[nr].cost=x;
                y=x;
                x=pred[x];
                pred[y]=0;
            }
        }
    }
    out<<nr<<"\n";
    for(i=1;i<=nr;i++)
        out<<sol[i].x<<" "<<sol[i].cost<<"\n";
    return 0;
}