Cod sursa(job #435759)

Utilizator alexandru92alexandru alexandru92 Data 7 aprilie 2010 20:49:05
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.6 kb
/* 
 * File:   main.cpp
 * Author: VirtualDemon
 *
 * Created on April 7, 2010, 8:38 PM
 */
#include <queue>
#include <cstdlib>
#include <fstream>
#include <iterator>
#define Nmax 100001

/*
 * 
 */
using namespace std;
struct vertex
{
    int first, second;
    vertex* next;
} *G[Nmax];
vector< int > d;
vector< bool > inH, was;
class cmp
{
public :
    inline bool operator() ( const int& x, const int& y ) const
    {
        return d[x] > d[y];
    }
};
priority_queue< int, vector<int>, cmp > H;
inline void add( const int& x, const int& y, const int& c )
{
    vertex* q=new vertex;
    q->first=y; q->second=c;
    q->next=G[x];
    G[x]=q;
}
int main( void )
{
    vertex* it;
    int N, M, x, y, c;
    ifstream in( "dijkstra.in" );
    in>>N>>M;
    for( ; M; --M )
    {
        in>>x>>y>>c;
        --x, --y;
        add( x, y, c );
    }
    d.resize(N);
    inH.resize(N);
    was.resize(N);
    for( H.push(0); !H.empty(); H.pop() )
    {
        x=H.top();
        inH[x]=false;
        for( it=G[x];  it; it=it->next )
        {
            y=it->first, c=it->second;
            if( !was[y] )
            {
                d[y]=d[x]+c;
                H.push(y);
                inH[y]=was[y]=true;
                continue;
            }
            if( d[y] > d[x]+c )
            {
                d[y]=d[x]+c;
                if( !inH[y] )
                {
                    H.push(y);
                    inH[y]=true;
                }
            }
        }
    }
    ofstream out( "dijkstra.out" );
    copy( d.begin()+1, d.end(), ostream_iterator<int>( out, " " ) );
    out<<'\n';
    return EXIT_SUCCESS;
}