Cod sursa(job #3374385)

Utilizator cristian___Nastase Cristian-Florin cristian___ Data 8 noiembrie 2026 23:39:50
Problema Sate Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.25 kb
#include <vector>
#include <fstream>
#include <stack>

using namespace std;

int main() {
    int n, m, x, y, i, j;

    ifstream in("sate.in");
    ofstream out("sate.out");

    in>>n>>m>>x>>y;

    vector<vector<int>> matrice;
    vector<bool> visited;

    for (i = 0; i <= n; i++) {
        vector<int> v;
        for (j = 0; j <= n; j++) {
            v.push_back(0);
        }
        matrice.push_back(v);

        visited.push_back(0);
    }

    int d;

    while (in>>i>>j>>d) {
        matrice[i][j] = d;
        matrice[j][i] = d;
    }

    in.close();

    stack<int> s;
    s.push(x);
    for (i = 1; i <= n; i++) {
        if (matrice[x][i] != 0) {
            s.push(i);
        }
    }

    visited[x] = 1;

    int suma = 0;

    while (!s.empty()) {
        int next = s.top();
        s.pop();

        if (x > next) {
            suma -= matrice[x][next];
        }
        else {
            suma += matrice[x][next];
        }

        if (next == y) {
            break;
        }

        x = next;
        visited[x] = 1;

        for (i = 1; i <= n; i++) {
            if (matrice[x][i] != 0 && !visited[i]) {
                s.push(i);
                visited[i] = 1;
            }
        }
    }

    out<<suma;
    out.close();

    return 0;
}