Cod sursa(job #1065522)

Utilizator Athena99Anghel Anca Athena99 Data 23 decembrie 2013 14:08:50
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.34 kb
#include <fstream>
#include <queue>
#include <vector>

using namespace std;

ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");

const int inf= 1<<30;
const int nmax= 50000;

int d[nmax+10];
bool u[nmax+10];

struct str {
    int x, y;
};
vector <str> v[nmax+10];

struct str_cmp {
    bool operator() ( const str &x, const str &y ) {
        return x.y>y.y;
    }
};

priority_queue <str, vector <str>, str_cmp> q;

inline str mp( int x, int y ) {
    str sol;
    sol.x= x;
    sol.y= y;
    return sol;
}

void dijkstra(  ) {
    q.push(mp(1,0));
    while ( !q.empty() ) {
        str x= q.top();
        q.pop();
        u[x.x]= 0;
        for ( int i= 0; i<(int)v[x.x].size(); ++i ) {
            if ( d[x.x]+v[x.x][i].y<d[v[x.x][i].x] ) {
                d[v[x.x][i].x]= d[x.x]+v[x.x][i].y;
                if ( u[v[x.x][i].x]==0 ) {
                    u[v[x.x][i].x]= 1;
                    q.push( mp(v[x.x][i].x, d[v[x.x][i].x]) );
                }
            }
        }
    }

}

int main(  ) {
    int n, m;
    fin>>n>>m;
    for ( ; m>0; --m ) {
        int a, b, c;
        fin>>a>>b>>c;
        v[a].push_back( mp(b,c) );
    }

    for ( int i= 2; i<=n; ++i ) {
        d[i]= inf;
    }

    dijkstra();

    for ( int i= 2; i<=n; ++i ) {
        if ( d[i]==inf ) {
            d[i]= 0;
        }
        fout<<d[i]<<" ";
    }

    return 0;
}