Pagini recente » Cod sursa (job #2052055) | Cod sursa (job #1385595) | Cod sursa (job #1642616) | Cod sursa (job #2912699) | Cod sursa (job #3258685)
#include <fstream>
#include <vector>
#include <queue>
#define NMAX 50002
#define INF (1<<30)
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int N,M,f[NMAX*10];
vector <int> cost(NMAX,INF);
vector<vector<pair<int,int>>> graph(NMAX);
queue <int> q;
void citire()
{
int x,y,c;
fin>>N>>M;
for(int i=1; i<=M; i++)
{
fin>>x>>y>>c;
graph[x].push_back({y,c});
}
}
int main()
{
citire();
cost[1]=0;
q.push(1);
while(!q.empty())
{
int nod=q.front();
q.pop();
for(int i=0; i<graph[nod].size(); i++)
{
if(cost[graph[nod][i].first]>cost[nod]+graph[nod][i].second)
{
cost[graph[nod][i].first]=cost[nod]+graph[nod][i].second;
q.push(graph[nod][i].first);
f[graph[nod][i].first]++;
if(f[graph[nod][i].first]>N)
{
fout<< "Ciclu negativ!" << "\n";
return 0;
}
}
}
}
for(int i=2; i<=N; i++)
{
fout<< cost[i] << " ";
}
fout<< "\n";
return 0;
}