Cod sursa(job #767113)

Utilizator test_666013Testez test_666013 Data 12 iulie 2012 19:47:47
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.66 kb
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
#define MAX 50005
#define INF 0xfffffff

vector<pair<int,int> >g[MAX];
struct comp{ int c,x; }h[MAX];

int n,d[MAX],pos[MAX],nr;

void remove(){
    pos[ h[1].x ] = 0;
    h[1] = h[nr--];

    int t = 1,f = 2;
    if( nr > 2 && h[3].c < h[2].c )f++;
    while( f <= nr && h[t].c > h[f].c )
    {
        swap( h[t],h[f] );
        swap( pos[ h[t].x ],pos[ h[f].x ] );
        t = f; f = 2*t;
        if( f+1 <= nr && h[f+1].c < h[f].c )f++;
    }
}

void update(int c,int x){
    int t,f;

    if( pos[x] == 0 )
    {
        nr++;
        h[nr].c = c;
        h[nr].x = x;
        pos[x] = nr;
        f = nr;
    } else {
        h[ pos[x] ].c = c;
        f = pos[x];
    }

    t = f/2;

    while( t > 0 && h[t].c > h[f].c )
    {
        swap( h[t],h[f] );
        swap( pos[ h[t].x ],pos[ h[f].x ] );
        f = t; t = f/2;
    }
}



void dijkstra(){
    int x,y;
    for(int i=2;i<=n;i++) d[i] = INF;
    nr = 1;
    h[1].c = 0; h[1].x = 1;
    while( nr > 0 )
    {
        x = h[1].x;
        remove();
        for(int i=0;i<g[x].size();i++)
        {
            y = g[x][i].second;
            if( d[y] > d[x] + g[x][i].first )
            {
                d[y] = d[x] + g[x][i].first;
                update(d[y],y);
            }
        }
    }
}

int main(){
    int m,x,y,c;
    freopen("dijkstra.in","r",stdin);
    freopen("dijkstra.out","w",stdout);
        scanf("%d %d",&n,&m);
        while(m--)
        {
            scanf("%d %d %d",&x,&y,&c);
            g[x].push_back( make_pair(c,y) );
        }
    dijkstra();
    for(int i=2;i<=n;i++)printf("%d ",d[i] == INF ? 0 : d[i]);

    return 0;
}