Pagini recente » Cod sursa (job #2054580) | Cod sursa (job #1305787) | Cod sursa (job #1253066) | Cod sursa (job #2054566) | Cod sursa (job #1207098)
/*#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
#include <algorithm>
#include <cassert>
using namespace std;
ifstream is ("bellmanford.in");
ofstream os ("bellmanford.out");
const int MAX_N = 50005;
const int INF = 0x3f3f3f3f;
vector < pair <int, int> > V[MAX_N];
queue <int> Q;
bool in_queue[MAX_N];
vector <int> dist(MAX_N, INF), cnt_in_queue(MAX_N, 0);
int negative_cycle = false;
int n, m;
int main()
{
is >> n >> m;
for (int i = 1; i <= m; ++ i)
{
int x, y, c;
is >> x >> y >> c;
V[x].push_back(make_pair(y, c));
}
dist[1] = 0, Q.push(1);
while (!Q.empty() && !negative_cycle)
{
int x = Q.front();
Q.pop();
in_queue[x] = false;
if (dist[x] < INF)
for (unsigned i = 0; i < V[x].size(); ++ i)
{
if (dist[V[x][i].first] > dist[x] + V[x][i].second)
{
dist[V[x][i].first] = dist[x] + V[x][i].second;
if (!in_queue[V[x][i].first])
{
if (cnt_in_queue[V[x][i].first] > n)
negative_cycle = true;
else
{
Q.push(V[x][i].first);
in_queue[V[x][i].first] = true;
cnt_in_queue[V[x][i].first] ++;
}
}
}
}
}
if (!negative_cycle)
{
for (int i = 2; i <= n; ++ i)
os << dist[i] << " ";
}
else
os << "Ciclu negativ!\n";
return 0;
}
*/
#include <fstream>
#include <queue>
#include <vector>
#define INF 0x3f3f3f
using namespace std;
ifstream is ("bellmanford.in");
ofstream os ("bellmanford.out");
vector <pair <int, int> > V[50001];
vector <int> cnt(50001, 0), d(50001, INF);
vector <bool> in_queue(50001, false);
queue <int> Q;
int n, m;
bool inf;
void Read();
void BellmanFord();
int main()
{
Read();
BellmanFord();
if(inf)
os << "Ciclu negativ!";
else
for(int i = 2; i <= n; ++i)
os << d[i] << ' ';
return 0;
}
void Read()
{
int x, y, z;
is >> n >> m;
for(int i = 1; i <= m; ++i)
{
is >> x >> y >> z;
V[x].push_back(make_pair(y, z));
}
d[1] = 0;
Q.push(1);
}
void BellmanFord()
{
int nod;
while(!Q.empty())
{
nod = Q.front();
Q.pop();
in_queue[nod] = false;
if(d[nod] < INF)
{
for(unsigned i = 0; i < V[nod].size(); ++i)
{
if(d[V[nod][i].first] > d[nod] + V[nod][i].second)
{
d[V[nod][i].first] = d[nod] + V[nod][i].second;
if(cnt[V[nod][i].first] > n)
inf = true;
else
{
Q.push(V[nod][i].first);
cnt[V[nod][i].first]++;
in_queue[V[nod][i].first] = true;
}
}
}
}
}
}