Cod sursa(job #2231049)

Utilizator DenisacheDenis Ehorovici Denisache Data 12 august 2018 19:35:32
Problema Xor Max Scor 25
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.78 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>
#include <cmath>
#include <bitset>
#include <set>

using namespace std;

string toBinaryString(int x) {
	string binaryRepr = "";

	while (x > 0) {
		binaryRepr += char('0' + (x & 1));
		x >>= 1;
	}

	if (binaryRepr.empty()) binaryRepr = "0";

	return binaryRepr + string(22 - binaryRepr.size(), '0');
}

struct BestXorInfo {
	int Value;
	int Position;
};

class TrieNode {
	BestXorInfo xorInfo;
	vector< TrieNode* > children;

public:
	TrieNode() {
		children.resize(2);
	}

	void Insert(string& insertedString, const BestXorInfo& insertedInfo) {
		if (insertedString.empty()) {
			this->xorInfo.Value = insertedInfo.Value;
			this->xorInfo.Position = max(this->xorInfo.Position, insertedInfo.Position);
			
			return;
		}

		char lastChar = insertedString.back();
		insertedString.pop_back();

		if (children[lastChar - '0'] == nullptr) {
			children[lastChar - '0'] = new TrieNode();
		}

		children[lastChar - '0']->Insert(insertedString, insertedInfo);
	}

	BestXorInfo GetBestXor(string& queriedString) {
		if (queriedString.empty()) {
			return xorInfo;
		}

		char lastChar = queriedString.back();
		queriedString.pop_back();

		if (children[1 - (lastChar - '0')] != nullptr)
			return children[1 - (lastChar - '0')]->GetBestXor(queriedString);
		else if (children[lastChar - '0'] != nullptr)
			return children[lastChar - '0']->GetBestXor(queriedString);
	}
};

class Trie {
	TrieNode root;

public:
	void Insert(string& insertedString, const BestXorInfo& insertedInfo) {
		root.Insert(insertedString, insertedInfo);
	}

	BestXorInfo GetBestXor(string& queriedString) {
		return root.GetBestXor(queriedString);
	}
};

int main() {
	freopen("xormax.in", "r", stdin);
	freopen("xormax.out", "w", stdout);

	ios::sync_with_stdio(false);

	int n;
	cin >> n;

	int currentXor = 0;

	int bestXor = 0;
	int bestLeft = -1;
	int bestRight = -1;

	Trie trie;
	string zeroRepr = toBinaryString(0);
	trie.Insert(zeroRepr, { 0, 0 });

	for (int i = 1; i <= n; ++i) {
		int x;
		cin >> x;

		currentXor ^= x;
		
		string binaryRepr = toBinaryString(currentXor);
		string auxRepr = binaryRepr;

		BestXorInfo bestXorInfo = trie.GetBestXor(auxRepr);
		trie.Insert(binaryRepr, { currentXor, i });

		if ((currentXor ^ bestXorInfo.Value) > bestXor) {
			bestXor = currentXor ^ bestXorInfo.Value;
			bestLeft = bestXorInfo.Position + 1;
			bestRight = i;
		}
		else if ((currentXor ^ bestXorInfo.Value) == bestXor && i - bestXorInfo.Position - 1 < bestRight - bestLeft) {
			bestLeft = bestXorInfo.Position + 1;
			bestRight = i;
		}
	}

	cout << bestXor << " " << bestLeft << " " << bestRight;

	//system("pause");
	return 0;
}