Cod sursa(job #3323364)

Utilizator g.vladGociu Vlad g.vlad Data 18 noiembrie 2025 10:07:28
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.58 kb

#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>

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

struct neighbour_t {
    long long dist = 0;
    unsigned idx;

    neighbour_t(unsigned idx, long long dist):
        dist(dist),
        idx(idx)
    {}
};

struct node_t {
    std::vector<neighbour_t> neighbours;
};

long long sate_dist(node_t* const graph, bool* const checked, unsigned const at, unsigned const target, long long const dist) {
    checked[at] = true;

    for(neighbour_t neighbour : graph[at].neighbours) {
        if(checked[neighbour.idx]) continue;

        if(neighbour.idx == target) {
            return dist + neighbour.dist;
        }

        long long new_dist = sate_dist(graph, checked, neighbour.idx, target, dist + neighbour.dist);

        if(new_dist != -1) return new_dist;
    }

    return -1;
}

int main() {
    unsigned nodes, edges, start, end;

    in >> nodes >> edges >> start >> end;

    if(start == end) {
        out << "0";
        return 0;
    }

    if(start > end) {
        unsigned _ = start;
        start = end;
        end = _;
    }

    node_t graph[30001];
    bool checked[30001];

    std::memset(checked, 0, 30001);

    unsigned a, b;
    long long d;
    for(unsigned edge = 0; edge < edges; edge += 1) {
        in >> a >> b >> d;
        graph[a].neighbours.push_back( neighbour_t(b, d) );
        graph[b].neighbours.push_back( neighbour_t(a, -d) );
    }

    out << sate_dist(graph, checked, start, end, 0);
}