Cod sursa(job #3188746)

Utilizator juincPopescu Marian juinc Data 3 ianuarie 2024 19:38:32
Problema Sate Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.32 kb
#include <fstream>
#include <queue>
#include <vector>

using namespace std;

const long long INF = 1e18;

vector<pair<int, long long>> adj[200005];
long long distances[200005];

void BFS(int node) {
    fill(distances, distances + 200005, 0);
    queue<int> q;

    distances[node] = 0;
    q.push(node);

    while (!q.empty()) {
        int current = q.front();
        q.pop();

        for (auto neighbor : adj[current]) {
            int nextNode = neighbor.first;
            long long weight = neighbor.second;

            if (distances[nextNode] == 0) {
                if (current > nextNode)
                    distances[nextNode] = distances[current] - weight;
                else
                    distances[nextNode] = distances[current] + weight;

                q.push(nextNode);
            }
        }
    }
}

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

    long long nodes, edges, root, goal;
    fin >> nodes >> edges >> root >> goal;

    for (int k = 1; k <= edges; ++k) {
        int i, j;
        long long D;
        fin >> i >> j >> D;
        adj[i].push_back({ j, D });
        adj[j].push_back({ i, D });
    }

    if (root > goal) swap(root, goal);
    BFS(root);
    fout << abs(distances[goal]) << '\n';

    return 0;
}