Pagini recente » Cod sursa (job #1360275) | Borderou de evaluare (job #508729) | Cod sursa (job #2752194) | Cod sursa (job #2036093) | Cod sursa (job #951494)
Cod sursa(job #951494)
#include<iostream>
#include<fstream>
#include<vector>
#include<queue>
#include<bitset>
using namespace std;
const int INF=0x3f3f3f3f;
const int MAXN=50005;
vector<pair<int, int> > adj[MAXN];
vector<int> adjt[MAXN];
int main()
{
ifstream in ("bellmanford.in");
int n,m,i,x,y,c;
in>>n>>m;
for(i=0;i<m;i++)
{
in>>x>>y>>c;
adj[x].push_back(make_pair(y,c));
adjt[x].push_back(y);
}
in.close();
queue <int> q;
bitset <MAXN> inq(0);
vector <int> dist(MAXN,INF),counter(MAXN,0);
int negative=0;
dist[1]=0;q.push(1);inq[1]=1;
while(!q.empty() && !negative)
{
x=q.front();q.pop();inq[x]=0;
vector<pair<int, int> >::iterator it;
for(it=adj[x].begin();it!=adj[x].end();it++)
if(dist[x]<INF)
if(dist[it->first]>dist[x]+it->second)
{
dist[it->first]=dist[x]+it->second;
if(!inq[it->first])
if(counter[it->first]>n) negative=1;
else
{
q.push(it->first);
inq[it->first]=1;
counter[it->first]++;
}
}
}
ofstream out("bellmanford.out");
if(negative)
cout<<"Ciclu negativ!\n";
else
for(i=2;i<=n;i++)
out<<dist[i]<<" ";
}