Cod sursa(job #3374522)

Utilizator Costin707Geamanu Constantin Costin707 Data 9 noiembrie 2026 01:43:56
Problema Sate Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.94 kb
#include <fstream>
#include <vector>
#include <queue>
#include <cmath>

using namespace std;

const int BUF_SIZE = 4096;
char buf[BUF_SIZE];
int posBuf = BUF_SIZE;

FILE *fin;

inline int readInt() {
    while (posBuf < BUF_SIZE && buf[posBuf] <= ' ') {
        posBuf++;
    }
    if (posBuf == BUF_SIZE) {
        fread(buf, 1, BUF_SIZE, fin);
        posBuf = 0;
        while (posBuf < BUF_SIZE && buf[posBuf] <= ' ') {
            posBuf++;
        }
    }

    int res = 0;
    while (posBuf < BUF_SIZE && buf[posBuf] >= '0' && buf[posBuf] <= '9') {
        res = res * 10 + (buf[posBuf] - '0');
        posBuf++;
        if (posBuf == BUF_SIZE) {
            fread(buf, 1, BUF_SIZE, fin);
            posBuf = 0;
        }
    }
    return res;
}

struct Muchie {
    int vecin;
    int dist;
};

const int MAXN = 30005;

vector<Muchie> adj[MAXN];
int dist_pos[MAXN];
bool vizitat[MAXN];

void bfs(int start, int target) {
    queue<int> q;
    
    q.push(start);
    vizitat[start] = true;
    dist_pos[start] = 0;

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

        if (u == target) return;

        for (const auto& edge : adj[u]) {
            int v = edge.vecin;
            int d = edge.dist;

            if (!vizitat[v]) {
                vizitat[v] = true;
                dist_pos[v] = dist_pos[u] + d;
                q.push(v);
            }
        }
    }
}

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

    int N = readInt();
    int M = readInt();
    int X = readInt();
    int Y = readInt();

    for (int k = 0; k < M; ++k) {
        int i = readInt();
        int j = readInt();
        int d = readInt();

        adj[i].push_back({j, d});
        adj[j].push_back({i, -d});
    }

    fclose(fin);

    bfs(X, Y);

    fout << abs(dist_pos[Y] - dist_pos[X]) << "\n";
    fout.close();

    return 0;
}