Cod sursa(job #3371860)

Utilizator nstefanNeagu Stefan nstefan Data 1 noiembrie 2026 11:43:32
Problema Sate Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.29 kb
// AI usage: Doar explicații


#include <bits/stdc++.h>
using namespace std;

#ifdef INFOARENA
ifstream fin("sate.in");
ofstream fout("sate.out");
#define cin fin
#define cout fout
#endif

struct Neighbor {
  int node;
  int cost;
};

using Graph = vector<vector<Neighbor>>;

int main() { 
  int n, m, startNode, endNode;
  cin >> n >> m >> startNode >> endNode;
  Graph g(n + 1);

  for (int i = 1; i <= m; i++) {
    int from, to, cost;
    cin >> from >> to >> cost;
    g[from].push_back({ to, cost });
    g[to].push_back({ from, -cost });
  }

  if (startNode > endNode) 
    swap(startNode, endNode);

  // start parcurgere


  // urasc prog compet
  // for (int node = 1; node <= n; node++)
  //   for (auto neigh : g[node])
  //     cout << node << ' ' << neigh.node << " " << neigh.cost << '\n';

  // { cost from 1 to node, node }
  using ii = tuple<int, int>;
  deque<ii> dq;
  vector<int> visited(n + 1);

  dq.push_back({ 0, startNode });

  while (!dq.empty()) {
    auto [cost, node] = dq.front();
    dq.pop_front();

    if (visited[node])
      continue;
    visited[node] = 1;

    if (node == endNode) {
      cout << cost << std::endl;
      return 0;
    }

    for (auto neigh : g[node])
      if (!visited[neigh.node]) {
        dq.push_back({ cost + neigh.cost, neigh.node });
      }
  }
}