HackerRank

The Editorial provides a Fast Fourier Transformation solution O(nlgn)... which is too maths for me. In the leaderboard, I found a not-that-fast O(n^2) solution, with a very smart observation.

#include <cstdio>
#include <cstring>
#include <iostream>
#include <sstream>
#include <set>
#include <string>
#include <algorithm>
#include <vector>
#include <unordered_map>
#include <unordered_set>
using namespace std;

#define MAX_CNT 100001
#define MAX_VAL 65536

int main()
{
    ios_base::sync_with_stdio(false);
    vector<int> pre(MAX_VAL);
    vector<int> cnt(MAX_VAL);

    int n; cin >> n;
    vector<int> nums(n);

    int sofar = 0;
    pre[sofar] ++;

    for (int i = 0; i < n; i++)
    {
        cin >> nums[i];
        sofar ^= nums[i];
        pre[sofar] ++;
    }

    //    consecutive ret[i, j] = pre[i] ^ pre[j]
    for (int i = 0; i < MAX_VAL; i++)
    for (int j = i + 1; j < MAX_VAL; j++)
    {
        cnt[i ^ j] += pre[i] * pre[j];
    }

    int best = 0;
    for (int i = 1; i < MAX_VAL; i ++)
    if (cnt[i] > cnt[best])
        best = i;
    cout << best << " " << cnt[best] << endl;
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/tonix/p/4599853.html