Cod sursa(job #1706663)

Utilizator tiberiu1995Arsene Constantin-Tiberiu tiberiu1995 Data 22 mai 2016 22:33:47
Problema Algoritmul lui Dijkstra Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.12 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
const int inf = 1000000;
const int NMAX = 251000;
int n,m;
int d[NMAX];
vector <int> graph[NMAX], cost[NMAX];
void Bellman_Ford(int vertex)
 {  queue <int> q;
    int c, x, y, length;

    for (int i=1;i<=n;i++)
        d[i]=inf;
    d[vertex]=0;
    q.push(vertex);
    while(!q.empty())
    {   x=q.front();
        q.pop();
        length=graph[x].size();
        for (int i = 0; i < length; i++)
        {   y=graph[x][i];
            c=cost[x][i];
            if (d[y]>d[x]+c)
            {   d[y]=d[x]+c;
                q.push(y);
            }
        }
    }
}
void afisare()
{   for (int i = 1; i <= n; i++)
    {   if (i == 1) continue;
        if (d[i] == inf) d[i] = 0;
        g<<d[i]<<' ';
    }
    g << '\n';
}

int main()
{   int x,y,z;
    f>>n>>m;
    for (int i = 1; i <= m; i++)
    {   f>>x>>y>>z;
        graph[x].push_back(y);
        cost[x].push_back(z);
    }
    Bellman_Ford(1);
    afisare();
    return 0;
}