XOR subsequences

You are given an array A consisting of N integers. Your task is to find the longest subsequence S, such that XOR of any two elements in S is non-zero.

You are required to print the size of S(L) and the array of indices that are chosen for S. In the case of multiple such arrays, choose the lexicographically smallest array.

Example: Let array A be [7, 9, 7], the maximum length of subsequence can be 2. There are two ways to choose a subsequence, [7, 9] and [9, 7]. The indices selected in the first case are [1, 2] while in the second they are [2, 3] so we need to choose [1, 2] as it is minimal.

Example:

Input:  n = 5, arr = {3, 2, 3, 1, 2}

Output:

3 1 2 4

Approach:

C++

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

vector<intxorSubsequence(int nvector<intarr)
{
    set<intst;
    vector<intres;
    for (int i = 0i < ni++)
    {
        if (st.find(arr[i]== st.end())
        {
            st.insert(arr[i]);
            res.push_back(i + 1);
        }
    }

    return res;
}
int main()
{

    int n = 5;
    vector<intarr = {32312};

    vector<intres = xorSubsequence(narr);
    cout << res.size() << "\n";

    for (int i = 0i < res.size(); i++)
        cout << res[i] << " ";
    cout << "\n";

    return 0;
}


No comments:

Post a Comment