Cod sursa(job #1317109)

Utilizator Vele_GeorgeVele George Vele_George Data 14 ianuarie 2015 16:17:37
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.28 kb
#include <iostream>
#include <vector>
#include <fstream>
#include <queue>
#define inf (1<<30)
using namespace std;

ifstream f("dijkstra.in");
ofstream go("dijkstra.out");
int n;

struct nod
{
  int a, c;
}aux;

vector< vector< nod > > g;
vector< bool > inq;
vector< int > dist;
queue < int > q;


void bellman(int x)
{
    dist[x]=0;
    q.push(x);
    while(!q.empty())
    {
        x=q.front();
          q.pop();
        inq[x]=false;
        for(int i=0; i<g[x].size(); i++)
        {
            int y = g[x][i].a;
            int cost=g[x][i].c;
            if (dist[x]+cost < dist[y])
            {
                dist[y]=dist[x]+cost;
                if(!inq[y])
                {
                    q.push(y);
                    inq[y]=true;
                }
            }
        }

    }
}



int main()
{
    int n,m,x;
    f>> n >> m;

    g.resize(n+1);
    for(int i=0; i<=n; i++)
    {
        inq.push_back(false);
        dist.push_back(inf);
    }


    for(int i=1; i<=m; i++)
    {
        f>>x >> aux.a >> aux.c;
        g[x].push_back(aux);
    }

    bellman(1);

    for(int i=2; i<=n; i++)
        if (dist[i]==inf) go <<"0 ";
                    else  go << dist[i] << " ";



    return 0;
}