AcWing 1414 cattle XOR

Title description:

Farmer John encountered a problem while feeding his cows.

He has N cows in total, numbered 1∼N.

Before each feeding, the N cows will stand in a row in the order of 1∼N.

In addition, each cow is assigned an integer that may not be unique.

Then all the allocated integers form an integer sequence of length N.

Please find a continuous non-empty subsequence in the integer sequence so that the XOR sum of the elements in the subsequence can be maximized.

If there are multiple such sequences, select the sequence with the lower cow number corresponding to the integer at the end of the sequence.

If there are still multiple alternative sequences, choose the one with the shortest length.

Input format

The first line contains the integer N.

In rows 2∼N+1, each row contains an integer, and the integer in row ii represents the integer value assigned to the cow numbered i−1.

Output format

Output three integers, respectively representing the largest XOR sum, the cow number corresponding to the integer at the beginning of the selected sequence, and the cow number corresponding to the integer at the end of the selected sequence.

data range

1≤N≤10^5,
the range of integers assigned to cows is [0,2^21−1].

Input sample:

5
1
0
5
4
2

Sample output:

6 4 5
#include <iostream>
#include <cstdio>

using namespace std;
const int MAX = 100009;

int son[MAX * 21][2]; // son[p][u] 表示结点编号为p的u儿子(这个题只有0 1两个儿子)的编号
int n, idx;
int s[MAX], id[MAX * 21];

void insert_trie(int num, int k)
{
    int p = 0;

    for(int i = 20; i >= 0; i--)
    {
        int u = num >> i & 1;
        if(!son[p][u])
            son[p][u] = idx++;
        p = son[p][u];
    }
    id[p] = k;
}

int query(int x)
{
    int p = 0;

    for(int i = 20; i>= 0; i--)
    {
        int u = x >> i & 1;
        if(son[p][!u])
            p = son[p][!u];
        else
            p = son[p][u];
    }
    return id[p];
}

int main()
{
    scanf("%d", &n);

    for(int i = 1; i <= n; i++)
    {
        scanf("%d", &s[i]);
        s[i] = s[i] ^ s[i - 1];
    }

    insert_trie(s[0], 0);

    int maxx = -1, l, r;

    for(int i = 1; i <= n; i++)
    {
        int k = query(s[i]);

        int t = s[i] ^ s[k];
        if(t > maxx)
        {
            maxx = t;
            l = k + 1;
            r = i;
        }
        insert_trie(s[i], i);
    }

    printf("%d %d %d\n", maxx, l, r);

    return 0;
}

 

Guess you like

Origin blog.csdn.net/weixin_44620183/article/details/114059079
XOR