Cod sursa(job #2855861)

Utilizator mmocanuMocanu Mihai-Adrian mmocanu Data 22 februarie 2022 23:48:24
Problema Sate Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.33 kb
#include <stdio.h>
#include <vector>
#include <queue>
using namespace std;

#define MAX_N 50004

struct Edge {
  int node, cost;
};

vector<Edge> graph[MAX_N];

queue<int> bfsQueue;
int dist[MAX_N];
int contor[MAX_N];
int m, stop;

void addEdge(int a, int b, int cost) {
  if(a<b){
    graph[a].push_back({b, cost});
    graph[b].push_back({a, -cost});
  }else{
    graph[a].push_back({b, -cost});
    graph[b].push_back({a, cost});
  }
}

void bfs(int node) {
  int qFront;

  bfsQueue.push(node);
  dist[node] = 0;
  stop = 0;
  while (!bfsQueue.empty() && stop == 0) {
    qFront = bfsQueue.front();
    contor[qFront]++;
    if(contor[qFront]<m){
      for (const Edge& edge : graph[qFront])
        if (!dist[edge.node] || dist[edge.node] > dist[qFront] + edge.cost) {
          bfsQueue.push(edge.node);
          dist[edge.node] = dist[qFront] + edge.cost;
        }
    }else{
      stop = 1;
    }
    bfsQueue.pop();
  }

}

int main() {
  FILE *fin, *fout;
  fin = fopen("sate.in", "r");
  fout = fopen("sate.out", "w");

  int n, i, a, b, cost, x, y;
  fscanf(fin, "%d%d%d%d", &n, &m, &x, &y);
  for (i = 0; i < m; ++i) {
    fscanf(fin, "%d%d%d", &a, &b, &cost);
    addEdge(a, b, cost);
  }

  bfs(x);
  fprintf(fout, "%d ", dist[y]);

  fclose(fin);
  fclose(fout);
  return 0;
}