Cod sursa(job #3271664)

Utilizator InfinitumDanila Laurentiu Infinitum Data 26 ianuarie 2025 20:11:21
Problema Sate Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.69 kb
#include <bits/stdc++.h>
using namespace std;
ifstream f("sate.in");
ofstream g("sate.out");
#define cout g
const int NMAX = 30001;
int n, m, a, b, dist = 0;
bitset<NMAX> viz;  // To mark visited nodes
vector<pair<int, int>> v[NMAX];  // Adjacency list: {neighbor, weight}
pair<int, int> pa[NMAX];  // {parent, weight to parent}
queue<int> q;  // BFS queue: stores nodes

void bfs() {
    q.push(a);
    viz[a] = 1;
    pa[a] = {0, 0};  // Root node has no parent, cost is 0

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

        for (auto nod : v[cur]) {
            int nextNode = nod.first;
            int cost = nod.second;

            if (!viz[nextNode]) {
                viz[nextNode] = 1;
                pa[nextNode] = {cur, cost};  // Store parent and weight
                q.push(nextNode);

                if (nextNode == b) {
                    return;  // Stop BFS early if we reach the target
                }
            }
        }
    }
}

int main() {
    f >> n >> m >> a >> b;

    // Read the graph
    for (int i = 1; i <= m; i++) {
        int x, y, c;
        f >> x >> y >> c;
        v[x].push_back({y, c});
        v[y].push_back({x, c});
    }

    bfs();

    // Trace back from b to a to calculate the total distance
    int current = b;
    while (current != a) {
        int parent = pa[current].first;
        int weight = pa[current].second;

        if (current > parent) {
            dist += weight;  // Moving "forward"
        } else {
            dist -= weight;  // Moving "backward"
        }

        current = parent;  // Move to the parent node
    }

    cout << dist;
    return 0;
}