Cod sursa(job #3373062)

Utilizator romaanRoman Andrei Gabriel romaan Data 6 noiembrie 2026 00:01:58
Problema Sate Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.43 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>

using namespace std;

const int MAX_NODURI = 30005;

struct Muchie {
    int vecin;
    long long cost;
};

vector<Muchie> graf[MAX_NODURI];
long long distanta[MAX_NODURI];
bool vizitat[MAX_NODURI];

int main() {
    ifstream fin("sate.in");
    ofstream fout("sate.out");

    int n, m, x, y;
    fin >> n >> m >> x >> y;

    for (int i = 0; i < m; ++i) {
        int u, v;
        long long d;
        fin >> u >> v >> d;

        if (u > v) {
            swap(u, v);
        }

        graf[u].push_back({v, d});
        graf[v].push_back({u, -d});
    }

    queue<int> coada;
    vizitat[x] = true;
    distanta[x] = 0;
    coada.push(x);

    while (!coada.empty()) {
        int nod = coada.front();
        coada.pop();

        if (nod == y) {
            break; 
        }

        for (Muchie m_curenta : graf[nod]) {
            int vecin = m_curenta.vecin;
            long long cost = m_curenta.cost;

            if (!vizitat[vecin]) {
                vizitat[vecin] = true;
                distanta[vecin] = distanta[nod] + cost;
                coada.push(vecin);
            }
        }
    }

    long long raspuns = distanta[y];
    if (raspuns < 0) {
        raspuns = -raspuns;
    }

    fout << raspuns << "\n";

    fin.close();
    fout.close();

    return 0;
}