Pagini recente » Cod sursa (job #51299) | Cod sursa (job #2029626) | Cod sursa (job #2835903) | Cod sursa (job #3179858) | Cod sursa (job #2924692)
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
ifstream in ("bellmanford.in");
ofstream out ("bellmanford.out");
const int max_size = 5e4 + 1, INF = 2e9 + 1;
struct str{
int to, cost;
};
vector <str> mc[max_size];
int d[max_size], viz[max_size], n;
queue <int> q;
bool bfs ()
{
q.push(1);
while (!q.empty())
{
int nod = q.front();
q.pop();
viz[nod]++;
if (viz[nod] == n + 1)
{
return false;
}
for (auto f : mc[nod])
{
if (d[nod] + f.cost < d[f.to])
{
d[f.to] = d[nod] + f.cost;
q.push(f.to);
}
}
}
return true;
}
int main ()
{
int m;
in >> n >> m;
for (int i = 2; i <= n; i++)
{
d[i] = INF;
}
while (m--)
{
int x, y, z;
in >> x >> y >> z;
mc[x].push_back({y, z});
}
if (!bfs())
{
out << "Ciclu negativ!";
}
else
{
for (int i = 2; i <= n; i++)
{
out << d[i] << " ";
}
}
in.close();
out.close();
return 0;
}