Cod sursa(job #1373615)

Utilizator Vele_GeorgeVele George Vele_George Data 4 martie 2015 19:44:21
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.49 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#define inf (1<<30)

using namespace std;

struct nods
{
  int a,c;
}aux;

int n,m,x,y,c;

vector<vector<nods> > gf;
vector<bool> used,inq;
vector<int> dist;
queue<int> q;

void bellman(int x)
{
    dist[x]=0;
    q.push(x);
    inq.push_back(true);

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

                }
            }
        }
    }
}


int main()
{
    ifstream f("dijkstra.in");
    ofstream g("dijkstra.out");

    f >> n >> m;
    gf.resize(n+1);
    for(int i=0; i<=n; i++)
    {
        dist.push_back(inf);
        used.push_back(false);
        inq.push_back(false);
    }

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

    bellman(1);

    for(int i=2; i<=n; i++)
    {
        if (dist[i]!=inf) g << dist[i] << " ";
                     else g << "0 ";
    }


    f.close();
    g.close();

    return 0;
}