Cod sursa(job #1691571)

Utilizator PTAdrian64Pop-Tifrea Adrian PTAdrian64 Data 18 aprilie 2016 19:35:18
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.12 kb
#include <cstdio>
#include <queue>
#define nmax 50001
#include <vector>
#define INF 0x3f3f3f3f

using namespace std;

int M,N,cost[nmax],cnt[nmax];
bool in_q[nmax];
priority_queue <pair<int,int> > Q;
vector <pair<int,int> > G[nmax];

int main(){

  freopen("bellmanford.in","r",stdin);
  freopen("bellmanford.out","w",stdout);

  scanf("%d %d ",&N,&M);
  int x,y,z;

  while(M--){
    scanf("%d %d %d ",&x,&y,&z);
    G[x].push_back(make_pair(y,z));
  }

  for(x = 2;x <= N;x++)cost[x] = INF;

  bool ok = 0;
  Q.push(make_pair(0,1));
  in_q[1] = 1;
  while(!Q.empty() && ok == 0){
    x = Q.top().second;
    Q.pop();
    in_q[x] = 0;
    for(vector <pair<int,int> > :: iterator it = G[x].begin();it != G[x].end();++it){
      if(cost[it->first] > cost[x] + it->second){
	cost[it->first] = cost[x] + it->second;
	if(in_q[it->first] == 0){
	  if(cnt[it->first] == N){
	    ok = 1;
	    break;
	  }
	  in_q[it->first] = 1;
	  cnt[it->first]++;
	  Q.push(make_pair(-cost[it->first],it->first));
	}
      }
    }
  }

  if(ok)printf("Ciclu negativ!\n");
  else {
    for(x = 2;x <= N;x++)printf("%d ",cost[x]);
    printf("\n");
  }

  return 0;
  
}