Skip to content

[Round Trip II](https://cses.fi/problemset/task/1678/) #5

@ShenNaizhi

Description

@ShenNaizhi

Hello Ankit Priyarup, I have read and understood your code for problem site, but I encountered an issue while reproducing it:

Image

I made some modifications to your code and got an AC. Here is my submission: AC code
I also submitted your code: WA code
Hope that I didn't make a mistake with your code.

It seems that VJudge only allows users to check the submissions in the form of pictures. For convenience, I provide my code here:

// #undef LOCAL
// #undef LOCAL_IO

#include <bits/stdc++.h>
using i64 = long long;
using namespace std;

#ifdef LOCAL
#   define debug(x) cout << #x << " = " << x << endl
#   define debugv(v) do { cout << #v << ": ["; string delim = "";\
    for (const auto& e : v) cout << delim << e, delim = ", ";\
    cout << ']' << endl; } while (0)
#else
#   define debug(...) 12
#   define debugv(...) 12
#endif

// returns the source of the cycle, otherwise -1
int dfs(vector<vector<int>>& g, vector<bool>& vis, vector<bool>& unsol,
        int cur, vector<int>& ans, bool& found) {
    vis[cur] = true;
    int res = -1;
    for (int adj : g[cur]) {
        if (!vis[adj]) {
            res = dfs(g, vis, unsol, adj, ans, found);
        } else if (!unsol[adj]) {
            // the problem has guaranteed no loops
            ans = {adj, cur};
            return adj;
        }
        if (res != -1) {
            if (!found) ans.push_back(cur);
            if (cur == res) {
                found = true;
                reverse(ans.begin(), ans.end());
            }
            return res;
        }
    }
    unsol[cur] = true;
    return -1;
}

void solve() {
    int n, m;
    cin >> n >> m;
    vector<vector<int>> g(n + 1); // vertex: [1..n]
    for (int i = 0; i < m; i++) {
        int a, b;
        cin >> a >> b;
        g[a].push_back(b);
    }
    vector<bool> vis(n + 1), unsol(n + 1);
    vector<int> ans;
    bool found = false;
    for (int i = 1; i <= n; i++) {
        int succ = -1;
        if (!vis[i]) dfs(g, vis, unsol, i, ans, found);
        if (found) break;
        else ans.clear();
    }
    if (!found) {
        cout << "IMPOSSIBLE" << "\n";
    } else {
        cout << ans.size() << "\n";
        for (int i = 0; i < ans.size(); i++) cout << ans[i] << " \n"[i == ans.size() - 1];
    }
}

int main() {
    #ifdef LOCAL_IO
        freopen("t.in", "r", stdin);
        freopen("t.out", "w", stdout);
    #endif
    cin.tie(0);
    ios::sync_with_stdio(0);
    int _ = 1;
    // cin >> _;

    while (_--) {
        solve();
    }
    return 0;
}

Thank you again for your solution code!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions