C++ · Solution

Travelling Sales

This C++ solution uses simulation for Travelling Sales. Read the reasoning, inspect the code, or try your own test case below.

Graphs & treesSimulationC++35 lines
Solution224of 248
Download C++ file ↓ Search the library → Open full Code Lab ↗ Report an issue ↗

Approach

Simulation

Travelling Sales: follow the problem rules directly, maintaining the small set of values needed for each step and producing the answer after a single controlled pass.

Graphs & trees

Problem and code

Useful links.

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

View exact source file ↗
Implementation

travelling_sales.cpp

C++

    #include <bits/stdc++.h>
    using namespace std;
    int main(){
        ios::sync_with_stdio(0); cin.tie(0);
        int n, m; cin >> n >> m;
        vector<vector<int>> adj(n + 1);
        for(int i = 0; i < m; i++){
            int a, b; cin >> a >> b;
            adj[a].push_back(b); adj[b].push_back(a);
        }
        deque<int> dq;
        vector<int> dist(n + 1, INT_MAX);
        unordered_set<int> office;
        int k; cin >> k;
        for(int i = 0; i < k; i++){
            int c; cin >> c;
            office.insert(c);
        }
        dist[*office.begin()] = 0;
        dq.push_front(*office.begin());
        while(!dq.empty()){
            int cur = dq.front(); dq.pop_front();
            for(int nxt : adj[cur]){
                if(office.count(nxt) && dist[nxt] != 0){
                    dist[nxt] = 0;
                    dq.push_front(nxt);
                } else if(dist[cur] + 1 < dist[nxt]){
                    dist[nxt] = dist[cur] + 1;
                    dq.push_back(nxt);
                }
            }
        }
        int ans = *max_element(dist.begin() + 1, dist.end());
        cout << ans << '\n';
    }
        

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.