DMOJ · dmopc17c1p3

DMOPC '17 Contest 1 P3 - Hitchhiking Fun

This C++ solution uses graph traversal for DMOJ dmopc17c1p3 DMOPC '17 Contest 1 P3 - Hitchhiking Fun. Read the reasoning, inspect the code, or try your own test case below.

dmopc17c1p3Graphs & treesGraph traversalC++54 lines
Solution112of 248
Open official problem ↗ Download C++ file ↓ Search the library → Open full Code Lab ↗ Report an issue ↗

Approach

Graph traversal

Hitchhiking Fun lexicographic objective matches the code's minimum-danger then minimum-edge path calculation.

Graphs & trees

Problem and code

Useful links.

Written by benbenyaojifen. Try the problem first, then compare your approach with the code.

Open official problem ↗View exact source file ↗
Implementation

P_3_Hitchhiking_Fun.cpp

C++

    #include <bits/stdc++.h>
    using namespace std;
    using ll = long long;
    const int inf = 1e9;
    const long long INF = 1e17; //❄️
    int main() {
        ios::sync_with_stdio(0); cin.tie(0); 
        int n, m; cin >> n >> m;
        vector<vector<pair<int, int>>> adj(n + 1);
        for (int i = 0; i < m; i++) {
            int u, v, w; cin >> u >> v >> w;
            adj[u].push_back({v, w});
            adj[v].push_back({u, w});
        }
        vector<int> cnt(n + 1, inf);
        deque<int> dq;
        cnt[1] = 0;
        dq.push_front(1);
        while (!dq.empty()) {
            int u = dq.front(); dq.pop_front();
            for (auto [v, d] : adj[u]) {
                int nd = cnt[u] + d;
               if (nd < cnt[v]) {
                    cnt[v] = nd;
                    if (d == 0) {
                        dq.push_front(v);
                    } else {
                        dq.push_back(v);
                    }
               } 
            }
        }
        if (cnt[n] == inf) {
            cout << -1 << '\n';
            return 0;
        }
        vector<int> step(n + 1, inf);
        queue<int> q;
        step[1] = 0;
        q.push(1);
        while (!q.empty()) {
            int u = q.front(); q.pop();
            for (auto[v, d] : adj[u]) {
                if (cnt[u] + d == cnt[v]) {
                    if (step[u] + 1 < step[v]) {
                        step[v] = + step[u] + 1;
                        q.push(v);
                    }
                }
            }
        }
        cout << cnt[n] << " " << step[n] << '\n';
        return 0;
    }
        

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗Keep studying →

Test this problem

Run your code here.

Paste your code, run a test case, compare the output, or trace selected values.

Full trace, comparison & stress testing ↗
StatusReady
Output
No run yet.
Diagnostics
No diagnostics yet.

Each run is isolated and has strict limits. Passing one test does not guarantee the judge will accept the solution.