Cod sursa(job #2703624)

Utilizator Ionut2791Voicila Ionut Marius Ionut2791 Data 8 februarie 2021 20:36:53
Problema Sate Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.18 kb
#include <bits/stdc++.h>
#define ll long long
#define sz(x) (int)(x).size()
#define debug(v,n) for (int i = 1; i <= (n); ++i) cout << v[i] << " ";
#define next cout << '\n'
using namespace std;

const int N = 30005;
vector<set<pair<int,int>>> graf(N);
int n, m, x, y, ans;
bool in[N];

void findEnd(int nod, int dist) {
    if(nod >= y) {
        if(nod == y)
            ans = dist;
        return;
    }

    for (pair<int,int> a : graf[nod]) {
        int to = a.first, d = a.second;
        if(to > nod)
            findEnd(to, dist + d);
    }
}
struct cmp {
    bool operator()(int a, int b) {
        return sz(graf[a]) < sz(graf[b]);
    }
};
priority_queue<int, vector<int>, cmp> coada;

int main() {
   // ifstream fin("date.in.txt");
    ifstream fin("sate.in");
    ofstream fout("sate.out");
    fin >> n >> m >> x >> y;

    for (int i = 1; i <= m; ++i) {
        int a, b, d;
        fin >> a >> b >> d;
        graf[a].insert({b, d});
        graf[b].insert({a, d});

        if(in[a] == false) {
            in[a] = true;
            coada.push(a);
        }
        if(in[b] == false) {
            in[b] = true;
            coada.push(b);
        }
    }

    while(!coada.empty()) {
        int nod = coada.top();

        coada.pop();
        //cout << nod << ' ' << sz(graf[nod]) << '\n';
        pair<int,int> last = {-1, -1};
        for (pair<int,int> a : graf[nod]) {
            int to = a.first, d = a.second;

            if(last.first != -1) {
                if(last.first < nod && nod < to) {
                    graf[last.first].insert({to, last.second + d});
                    graf[to].insert({last.first, last.second + d});
                    //cout << to << " " << last.first << " " << last.second + d << '\n';
                    continue;
                }

                graf[last.first].insert({to, abs(last.second - d)});
                graf[to].insert({last.first, abs(last.second - d)});
                //cout << to << " " << last.first << " " << abs(last.second - d) << '\n';
            }
            last = {to, d};
        }
    }


    findEnd(x, 0);
    fout << ans << '\n';
    return 0;
}