Cod sursa(job #2231099)

Utilizator DenisacheDenis Ehorovici Denisache Data 12 august 2018 22:52:09
Problema Xor Max Scor 50
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.18 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>
#include <cmath>
#include <bitset>
#include <set>

using namespace std;

struct BestXorInfo {
	uint32_t Value;
	uint32_t Position;
};

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

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

	void Insert(char* insertedString, const BestXorInfo& insertedInfo) {
		if (*insertedString == '\0') {
			xorInfo = move(insertedInfo);
			return;
		}

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

		children[*insertedString - '0']->Insert(insertedString + 1, insertedInfo);
	}

	BestXorInfo GetBestXor(char* queriedString) {
		if (*queriedString == '\0') {
			return xorInfo;
		}

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

int main() {
	ios::sync_with_stdio(false);

	ifstream cin("xormax.in");
	ofstream cout("xormax.out");

	uint32_t n;
	cin >> n;

	uint32_t currentXor = 0;

	uint32_t bestXor = 0;
	uint32_t bestLeft = 0;
	uint32_t bestRight = 0;

	TrieNode* root = new TrieNode();

	BestXorInfo currentInfo;
	currentInfo.Value = 0;
	currentInfo.Position = 0;

	root->Insert(const_cast<char*>(bitset<22>(0).to_string().c_str()), currentInfo);

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

		currentXor ^= x;
		bitset<22> bs(currentXor);

		currentInfo.Value = currentXor;
		currentInfo.Position = i;

		root->Insert(const_cast<char*>(bs.to_string().c_str()), currentInfo);
		BestXorInfo bestXorInfo = root->GetBestXor(const_cast<char*>(bs.to_string().c_str()));

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

	if (bestLeft == 0) bestLeft = bestRight = 1;
	cout << bestXor << " " << bestLeft << " " << bestRight;

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