1876C - Autosynthesis - CodeForces Solution


constructive algorithms dfs and similar graphs

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>

#define rep(i, x, y) for(int i=x;i<=y;i++)
#define per(i, x, y) for(int i=x;i>=y;i--)
using namespace std;
#define dbg(x...) \
    do { \
        std::cout << #x << " -> "; \
        err(x); \
    } while (0)

void err() {
    std::cout << std::endl;
}

template<class T, class... Ts>
void err(T arg, Ts &... args) {
    std::cout << arg << ' ';
    err(args...);
}

const int N = 2e5 + 10;
const int mod = 998244353;
//const int mod = 1e9 + 7;
#define int long long
const int inf = 1e18;

int qmi(int a, int b) {
    int res = 1;
    for (; b; b >>= 1, a = a * a % mod) {
        if (b & 1)res = res * a % mod;
    }
    return res;
}

int n, vis[N], col[N], a[N];
vector<int> e[N];
bool flag = 1;

void dfs(int u) {
    for (auto v: e[u]) {
        if (col[v]) {
            if (col[v] != 3 - col[u])flag = 0;
        } else col[v] = 3 - col[u], dfs(v);
    }
}

void elysira() {
    cin >> n;
    rep(i, 1, n)cin >> a[i], vis[a[i]]++,e[i].push_back(a[i]);
    queue<int> q;
    rep(i, 1, n)if (!vis[i])q.push(i);
    while (not q.empty()) {
        auto u = q.front();
        q.pop();
        if (!col[a[u]]) {
            if (--vis[a[a[u]]] == 0)q.push(a[a[u]]);
        }
        col[u] = 1, col[a[u]] = 2;
    }
    rep(i, 1, n)if (!col[i])col[i] = 1, dfs(i);
    if (!flag)cout << "-1\n";
    else {
        vector<int> ans;
        rep(i, 1, n)if (col[i] == 1)ans.push_back(a[i]);
        cout << ans.size() << "\n";
        for (auto x: ans)cout << x << " ";
    }
}

signed main() {
    cin.tie(nullptr)->sync_with_stdio(false);
    int tc = 1;
    //cin >> tc;
    for (int i = 1; i <= tc; i++) {
        elysira();
    }
}
/*
*/
/*
*/
 	  	 			 	 			 	   					   			


Comments

Submit
0 Comments
More Questions

1714B - Remove Prefix
1264F - Beautiful Fibonacci Problem
52A - 123-sequence
1543A - Exciting Bets
1714D - Color with Occurrences
215B - Olympic Medal
1445A - Array Rearrangment
1351A - A+B (Trial Problem)
935B - Fafa and the Gates
1291A - Even But Not Even
1269A - Equation
441A - Valera and Antique Items
1702C - Train and Queries
816B - Karen and Coffee
838D - Airplane Arrangements
148B - Escape
847G - University Classes
1110A - Parity
1215B - The Number of Products
604C - Alternative Thinking
1204C - Anna Svyatoslav and Maps
322A - Ciel and Dancing
1689B - Mystic Permutation
1711B - Party
1702D - Not a Cheap String
1714F - Build a Tree and That Is It
1703F - Yet Another Problem About Pairs Satisfying an Inequality
610A - Pasha and Stick
1200A - Hotelier
1091A - New Year and the Christmas Ornament