DMOJ · sleigh

Sleigh Ride

This C++ solution uses graph traversal for DMOJ sleigh Sleigh Ride. Read the reasoning, inspect the code, or try your own test case below.

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

Approach

Graph traversal

Sleigh Ride matches the weighted tree and the minimum traversal formula twice total edge weight minus the farthest route.

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

sleigh_ride.cpp

C++

    #include <bits/stdc++.h>
    using namespace std;
    using ll = long long;
    using Edge = pair<int, ll>;
    vector<vector<Edge>> g;
    ll farDist;
    void dfs(int u, int p, ll acc){
        farDist = max(farDist, acc);
        for(auto [v, w] : g[u]){
            if(v == p) continue;
            dfs(v, u, acc + w);
        }
    }
    int main(){
        ios::sync_with_stdio(0);
        cin.tie(0);
        int m; cin >> m;
        vector<tuple<int,int,ll>> edges;
        edges.reserve(m);
        int maxv = 0;
        ll sumW = 0;
        for(int i = 0; i < m; i++){
            int u, v; ll w;
            cin >> u >> v >> w;
            edges.emplace_back(u, v, w);
            maxv = max(maxv, max(u, v));
            sumW += w;
        }
        int n = maxv + 1;
        g.assign(n, {});
        for(auto [u, v, w] : edges){
            g[u].push_back({v, w});
            g[v].push_back({u, w});
        }
        // Only need farthest distance from 0
        farDist = 0;
        dfs(0, -1, 0);
        ll ans = 2LL * sumW - farDist;
        cout << ans << "\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.