Pagini recente » Cod sursa (job #1839513) | Cod sursa (job #2427369) | Cod sursa (job #2424691) | Cod sursa (job #2423987)
#include <iostream>
#include <vector>
#include <queue>
#include <fstream>
#include <cassert>
#include <algorithm>
#include <cstring>
using namespace std;
const int nmax = 50005;
const int inf = 0x3f3f3f3f;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
vector <pair<int, int> > graph[nmax];
int dist[nmax];
bool inQueue[nmax];
int main()
{
int n,m;
f>>n>>m;
assert(1 <= n && n <= 50000);
assert(1 <= m && m <= 250000);
memset(dist, inf, sizeof dist);
for(int i = 1;i<=m;i++)
{
int from,to,cost;
f>>from>>to>>cost;
assert(1 <= from && from <= n);
assert(1 <= to && to <= n);
assert(0 <= cost && cost <= 20000);
graph[from].push_back(make_pair(to, cost));
}
dist[1] = 0;
queue <int> q;
q.push(1);
while (!q.empty())
{
int nod = q.front();
inQueue[nod] = false;
q.pop();
for(vector<pair<int, int> >::iterator it = graph[nod].begin(); it != graph[nod].end(); ++it)
{
int to = it->first;
int cost = it->second;
if(dist[to] > dist[nod] + cost)
{
dist[to] = dist[nod] + cost;
if(!inQueue[to])
{
inQueue[to] = true;
q.push(to);
}
}
}
}
for (int i = 2; i <= n; ++i) {
if (dist[i] == inf) {
dist[i] = 0;
}
g<<dist[i]<<" ";
}
f.close();
g.close();
return 0;
}