Problem p02809 (C++)

Buggy submission (status: Runtime Error):
#include <bits/stdc++.h>
#include <random>

using namespace std;

typedef unsigned long long ull;
typedef long long ll;
typedef long double ld;
// #define int ll
typedef pair<int, int> pii;
typedef pair<pii, pii> piii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;
typedef vector<pii> vpi;
typedef vector<vi> vvi;
typedef vector<vvi> vvvi;
typedef vector<short> vs;
typedef vector<vs> vvs;
typedef vector<vvs> vvvs;
typedef vector<ll> vl;
typedef vector<vl> vvl;
typedef vector<vvl> vvvl;
typedef vector<ld> vld;
typedef vector<vld> vvld;
typedef vector<vvld> vvvld;
typedef vector<string> vst;
typedef vector<vst> vvst;
typedef pair<ld, ld> pld;
typedef complex<double> base;

#define inmin(a, b) a = min(a, (b))
#define inmax(a, b) a = max(a, (b))
#define mp(a, b) make_pair((a), (b))
#define ALL(a) a.begin(), a.end()
#define RALL(a) a.rbegin(), a.rend()
#define sqr(x) ((x) * (x))
#define fori(i, n) for (int i = 0; i < int(n); ++i)
#define SZ(a) ((int)((a).size()))
#define triple(T) tuple<T, T, T>
#define quad(T) tuple<T, T, T, T>
#define watch(x) cerr << (#x) << " = " << (x) << endl;

#ifdef MAX_HOME
#define cerr cout
#else
#define cerr                                                                   \
  if (false)                                                                   \
  cerr
#endif

const double PI = 2 * acos(0.0);
#define rand shittttty_shit
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
mt19937_64 rng_64(chrono::steady_clock::now().time_since_epoch().count());

const string DIGITS = "0123456789";
const string ALPH = "abcdefghijklmnopqrstuvwxyz";

template <class T0, class T1>
inline ostream &operator<<(ostream &out, pair<T0, T1> &a) {
  return out << "{" << a.first << ", " << a.second << "}";
}

template <class T0, class T1, class T2>
inline ostream &operator<<(ostream &out, tuple<T0, T1, T2> &a) {
  return out << "{" << get<0>(a) << ", " << get<1>(a) << ", " << get<2>(a)
             << "}";
}

template <class T0, class T1, class T2, class T3>
inline ostream &operator<<(ostream &out, tuple<T0, T1, T2, T3> &a) {
  return out << "{" << get<0>(a) << ", " << get<1>(a) << ", " << get<2>(a)
             << ", " << get<3>(a) << "}";
}

template <class T> inline ostream &operator<<(ostream &out, vector<T> &a) {
  out << "[";
  fori(i, a.size()) out << a[i]
                        << vector<string>{", ", "]  "}[i + 1 == a.size()];
  return out;
}

void smain();

signed main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);

#ifdef MAX_HOME
  freopen("input.txt", "r", stdin);
  clock_t start = clock();
#endif
  cout << setprecision(12) << fixed;
  smain();
#ifdef MAX_HOME
  cout << "\n\n\n\nTOTAL EXECUTION TIME: "
       << float(clock() - start) / CLOCKS_PER_SEC << endl;
#endif
  return 0;
}

bool kek(vi a) {
  int n = a.size();
  int fr = -1;
  vi ns(n);
  fori(i, n) { ns[i] = i + 1; }

  vi p = ns;
  int ans = -1;
  do {
    bool ok = fr != p[0];
    fori(i, n - 1) {
      if (p[i + 1] == a[p[i] - 1]) {
        ok = false;
        break;
      }
    }
    if (ok) {
      if (ans == -1) {
        ans = p[0];
      } else if (ans != p[0]) {
        return true;
      }
    }
  } while (next_permutation(ALL(p)));

  return false;
}

vi naive(const vi &a, vi ns, int fr) {
  a.size();
  int n = ns.size();
  sort(ALL(ns));
  vi p = ns;
  vi ans = {};
  do {
    bool ok = fr != p[0];
    fori(i, n - 1) {
      if (p[i + 1] == a[p[i] - 1]) {
        ok = false;
        break;
      }
    }
    if (ok) {
      if (ans.empty()) {
        ans = p;
      } else if (ans > p) {
        ans = p;
      }
    }
  } while (next_permutation(ALL(p)));

  return ans;
}

void stress() {
  int cnt = -1;
  set<vi> samples;
  while (true) {
    if (++cnt % 50 == 0)
      watch(cnt);
    int n = 3 + rng() % 7;
    vi a(n);
    fori(i, n) {
      a[i] = rng() % (n - 1);
      if (a[i] == i)
        a[i]++;
      a[i]++;
    }
    if (!kek(a)) {
      set<int> kek;
      for (auto x : a) {
        kek.insert(x);
      }
      if (kek.size() != 2) {
        watch(a);
        break;
      }
    }
  }
}

void smain() {

  //    stress();

  int n;
  cin >> n;
  vi a(n);
  vi deg(n + 1, 0);
  fori(i, n) {
    cin >> a[i];
    deg[a[i]]++;
  }

  set<int> fre;
  for (int i = 1; i <= n; ++i) {
    fre.insert(i);
  }
  vi p;
  int fr = -1;
  set<pii> degver;
  for (int i = 1; i <= n; ++i) {
    degver.insert({deg[i], i});
  }
  for (int i = 0; n - i > 3; ++i) {
    auto it = fre.begin();
    if (*it == fr)
      ++it;

    int x = *it;

    if ((*degver.rbegin()).first == n - i - 1) {
      x = (*degver.rbegin()).second;
    }
    assert(fr != x);
    p.push_back(x);
    degver.erase({deg[x], x});
    if (fre.count(a[x])) {
      degver.erase({deg[a[x]], a[x]});
      deg[a[x]]--;
      degver.insert({deg[a[x]], a[x]});
    }

    fr = a[x - 1];
    fre.erase(x);
  }

  vi rest(ALL(fre));

  vi sol = naive(a, rest, fr);
  if (sol.empty()) {
    //        assert(n == 2);
    cout << "-1";
    return;
  }
  p.insert(p.end(), ALL(sol));
  for (auto x : p) {
    cout << x << ' ';
  }
}

Fixed submission:
#include <bits/stdc++.h>
#include <random>

using namespace std;

typedef unsigned long long ull;
typedef long long ll;
typedef long double ld;
// #define int ll
typedef pair<int, int> pii;
typedef pair<pii, pii> piii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;
typedef vector<pii> vpi;
typedef vector<vi> vvi;
typedef vector<vvi> vvvi;
typedef vector<short> vs;
typedef vector<vs> vvs;
typedef vector<vvs> vvvs;
typedef vector<ll> vl;
typedef vector<vl> vvl;
typedef vector<vvl> vvvl;
typedef vector<ld> vld;
typedef vector<vld> vvld;
typedef vector<vvld> vvvld;
typedef vector<string> vst;
typedef vector<vst> vvst;
typedef pair<ld, ld> pld;
typedef complex<double> base;

#define inmin(a, b) a = min(a, (b))
#define inmax(a, b) a = max(a, (b))
#define mp(a, b) make_pair((a), (b))
#define ALL(a) a.begin(), a.end()
#define RALL(a) a.rbegin(), a.rend()
#define sqr(x) ((x) * (x))
#define fori(i, n) for (int i = 0; i < int(n); ++i)
#define SZ(a) ((int)((a).size()))
#define triple(T) tuple<T, T, T>
#define quad(T) tuple<T, T, T, T>
#define watch(x) cerr << (#x) << " = " << (x) << endl;

#ifdef MAX_HOME
#define cerr cout
#else
#define cerr                                                                   \
  if (false)                                                                   \
  cerr
#endif

const double PI = 2 * acos(0.0);
#define rand shittttty_shit
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
mt19937_64 rng_64(chrono::steady_clock::now().time_since_epoch().count());

const string DIGITS = "0123456789";
const string ALPH = "abcdefghijklmnopqrstuvwxyz";

template <class T0, class T1>
inline ostream &operator<<(ostream &out, pair<T0, T1> &a) {
  return out << "{" << a.first << ", " << a.second << "}";
}

template <class T0, class T1, class T2>
inline ostream &operator<<(ostream &out, tuple<T0, T1, T2> &a) {
  return out << "{" << get<0>(a) << ", " << get<1>(a) << ", " << get<2>(a)
             << "}";
}

template <class T0, class T1, class T2, class T3>
inline ostream &operator<<(ostream &out, tuple<T0, T1, T2, T3> &a) {
  return out << "{" << get<0>(a) << ", " << get<1>(a) << ", " << get<2>(a)
             << ", " << get<3>(a) << "}";
}

template <class T> inline ostream &operator<<(ostream &out, vector<T> &a) {
  out << "[";
  fori(i, a.size()) out << a[i]
                        << vector<string>{", ", "]  "}[i + 1 == a.size()];
  return out;
}

void smain();

signed main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);

#ifdef MAX_HOME
  freopen("input.txt", "r", stdin);
  clock_t start = clock();
#endif
  cout << setprecision(12) << fixed;
  smain();
#ifdef MAX_HOME
  cout << "\n\n\n\nTOTAL EXECUTION TIME: "
       << float(clock() - start) / CLOCKS_PER_SEC << endl;
#endif
  return 0;
}

bool kek(vi a) {
  int n = a.size();
  int fr = -1;
  vi ns(n);
  fori(i, n) { ns[i] = i + 1; }

  vi p = ns;
  int ans = -1;
  do {
    bool ok = fr != p[0];
    fori(i, n - 1) {
      if (p[i + 1] == a[p[i] - 1]) {
        ok = false;
        break;
      }
    }
    if (ok) {
      if (ans == -1) {
        ans = p[0];
      } else if (ans != p[0]) {
        return true;
      }
    }
  } while (next_permutation(ALL(p)));

  return false;
}

vi naive(const vi &a, vi ns, int fr) {
  a.size();
  int n = ns.size();
  sort(ALL(ns));
  vi p = ns;
  vi ans = {};
  do {
    bool ok = fr != p[0];
    fori(i, n - 1) {
      if (p[i + 1] == a[p[i] - 1]) {
        ok = false;
        break;
      }
    }
    if (ok) {
      if (ans.empty()) {
        ans = p;
      } else if (ans > p) {
        ans = p;
      }
    }
  } while (next_permutation(ALL(p)));

  return ans;
}

void stress() {
  int cnt = -1;
  set<vi> samples;
  while (true) {
    if (++cnt % 50 == 0)
      watch(cnt);
    int n = 3 + rng() % 7;
    vi a(n);
    fori(i, n) {
      a[i] = rng() % (n - 1);
      if (a[i] == i)
        a[i]++;
      a[i]++;
    }
    if (!kek(a)) {
      set<int> kek;
      for (auto x : a) {
        kek.insert(x);
      }
      if (kek.size() != 2) {
        watch(a);
        break;
      }
    }
  }
}

void smain() {

  //    stress();

  int n;
  cin >> n;
  vi a(n);
  vi deg(n + 1, 0);
  fori(i, n) {
    cin >> a[i];
    deg[a[i]]++;
  }

  set<int> fre;
  for (int i = 1; i <= n; ++i) {
    fre.insert(i);
  }
  vi p;
  int fr = -1;
  set<pii> degver;
  for (int i = 1; i <= n; ++i) {
    degver.insert({deg[i], i});
  }
  for (int i = 0; n - i > 3; ++i) {
    auto it = fre.begin();
    if (*it == fr)
      ++it;

    int x = *it;

    if ((*degver.rbegin()).first == n - i - 1) {
      x = (*degver.rbegin()).second;
    }
    assert(fr != x);
    p.push_back(x);
    degver.erase({deg[x], x});
    if (fre.count(a[x - 1])) {
      degver.erase({deg[a[x - 1]], a[x - 1]});
      deg[a[x - 1]]--;
      degver.insert({deg[a[x - 1]], a[x - 1]});
    }

    fr = a[x - 1];
    fre.erase(x);
  }

  vi rest(ALL(fre));

  vi sol = naive(a, rest, fr);
  if (sol.empty()) {
    //        assert(n == 2);
    cout << "-1";
    return;
  }
  p.insert(p.end(), ALL(sol));
  for (auto x : p) {
    cout << x << ' ';
  }
}