CF Div2 1081 E

Sora avatar
Sora
c_cpp
02/21/2026 8:02 PM
2.3 KB
48
Indexable
#include <bits/stdc++.h>
using namespace std;

using ll = long long;

constexpr ll mod = 1e9+7;

void solve(){
    ll n; cin >> n;
    vector<ll> a(n); for (ll &i : a) cin >> i;
    vector<ll> b(n); for (ll &i : b) cin >> i;

    vector<set<ll>> idx(n+1);
    ll cnt = n;
    for (ll i = 0; i < n; i++){
        if (a[i] != b[i]){
            idx[a[i]].insert(i);
            idx[b[i]].insert(i);
        }  else cnt--;
    }

    // freq of each element needs to be even
    for (ll i = 1; i <= n; i++){
        if (idx[i].size() & 1) {cout << -1 << '\n'; return;}
    }

    // pick a num c1 for A, its corresponding number c2 goes to B
    // now pick that c2 for A, and its corresponding number c3 goes to B
    // c3 for A -> c4 to B
    // c4 for A -> c5 to B and so on...
    // after some operation number added to B might not be left anymore for A, that number is c1 only [extra number put in A]
    // now repeat this again.
    // keep repeating until numbers left to put!
    vector<ll> op;
    ll num = 1, aval = 1;
    while (cnt--){
        while (idx[aval].empty()) aval++;
        if (idx[num].empty()) num = aval;
        ll it = *idx[num].begin();
        if (a[it] == num){
            ll nxt = b[it];
            idx[num].erase(it);
            idx[nxt].erase(it);
            num = nxt;
        } else {
            op.push_back(it);
            ll nxt = a[it];
            idx[num].erase(it);
            idx[nxt].erase(it);
            num = nxt;
        }
    }
    cout << op.size() << '\n';
    for (ll i : op) cout << i+1 << " "; cout << '\n';
}

int main(){
    ios_base::sync_with_stdio(false); cin.tie(nullptr);

    ll t; cin >> t;
    while (t--) solve();
}

// TC -> O(N lg N)
// SC -> O(N)
Editor is loading...
Leave a Comment