Codeforces
CF Step
Youtube Linkedin Discord Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Code : Binary Spiders

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

#define endl "\n";

void solve(vector<int> &a, int k) {
    vector<int> a_copy = a;
    sort(a.begin(), a.end());

    int n = a.size();
    vector<int> dp(n, 0), parent(n, -1);

    // good subsequence : All pairs in subsequence have xor >= k.
    // dp[i] is the maximum good subsequence ending at i.

    // Fact : xor is minimized for adjacent elements in sorted list.
    dp[0] = 1;
    for (int i = 1; i < n; i++) {
        for (int j = 0; j < i; j++) {
            if ((a[i] ^ a[j]) >= k) {
                if (dp[i] <= 1 + dp[j]) {
                    dp[i] = 1 + dp[j];
                    parent[i] = j;
                }
            }
        }
    }

    auto max_ind = max_element(dp.begin(), dp.end()) - dp.begin();
    if (dp[max_ind] == 1) {
        cout << "-1" << endl;
        return;
    }

    set<int> take;
    int now = max_ind;
    while (now != -1) {
        take.insert(a[now]);
        now = parent[now];
    }

    cout << dp[max_ind] << endl;
    for (int i = 0; i < n; i++) {
        if (take.find(a_copy[i]) != take.end()) {
            cout << i + 1 << " ";
        }
    }
    cout << endl;
}

int main() {
    int n, k;
    cin >> n >> k;

    vector<int> a(n);
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }
    solve(a, k);
    return 0;
}