USER: chen chen [thestor1] TASK: cowxor LANG: C++ Compiling... Compile: OK Executing... Test 1: TEST OK [0.008 secs, 3500 KB] Test 2: TEST OK [0.011 secs, 3500 KB] Test 3: TEST OK [0.008 secs, 3500 KB] Test 4: TEST OK [0.005 secs, 3500 KB] Test 5: TEST OK [0.046 secs, 4952 KB] Test 6: TEST OK [0.089 secs, 6932 KB] Test 7: TEST OK [0.100 secs, 6008 KB] Test 8: TEST OK [0.127 secs, 10628 KB] Test 9: TEST OK [0.068 secs, 3500 KB] Test 10: TEST OK [0.057 secs, 3500 KB] Test 11: TEST OK [0.065 secs, 3500 KB] Test 12: TEST OK [0.103 secs, 6536 KB] Test 13: TEST OK [0.051 secs, 3500 KB] Test 14: TEST OK [0.095 secs, 3500 KB] Test 15: TEST OK [0.292 secs, 13532 KB] Test 16: TEST OK [0.262 secs, 13664 KB] Test 17: TEST OK [0.246 secs, 13664 KB] Test 18: TEST OK [0.162 secs, 11552 KB] Test 19: TEST OK [0.065 secs, 4952 KB] Test 20: TEST OK [0.005 secs, 3500 KB] All tests OK.
这道题还是看了大神们在topcoder上面的讨论知道怎么做的:http://apps.topcoder.com/forums/?module=Thread&threadID=507673&mc=25&view=flat
红色的lovro大神描述了算法的实现。这里也是完全照着做的,用一个二叉树表示,0向左,1向右。greedy的匹配是最优的,大神已经解释了前面匹配大于后面匹配之和,所以整个过程就是一个查找二叉树匹配的过程(不能匹配只能走另外一支了)。
/*
ID: thestor1
LANG: C++
TASK: cowxor
*/
#include <iostream>
#include <fstream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <climits>
#include <cassert>
#include <string>
#include <vector>
#include <list>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
#include <cassert>
using namespace std;
class Tree
{
public:
Tree *left, *right;
Tree() : left(NULL), right(NULL) {}
};
class Leaf : public Tree
{
public:
int index;
Leaf(int index) : index(index) {}
};
int main()
{
ifstream fin("cowxor.in");
int N;
fin >> N;
unsigned int num, xors = 0;
Tree *root = new Tree();
Tree *node;
int maxstart = 0, maxend = 0, maxxor = 0;
int val = 0;
// wether reached end
bool found;
for (int i = 0; i < N; ++i)
{
fin >> num;
xors ^= num;
if (xors > maxxor)
{
maxxor = xors;
maxstart = 0, maxend = i;
}
node = root;
val = 0;
found = true;
for (int b = 21; b >= 0; --b)
{
if (xors & (1 << b))
{
if (node->left)
{
node = node->left;
val += 1 << b;
}
else if (node->right)
{
node = node->right;
}
else
{
found = false;
break;
}
}
else
{
if (node->right)
{
node = node->right;
val += 1 << b;
}
else if (node->left)
{
node = node->left;
}
else
{
found = false;
break;
}
}
}
if (found)
{
int start = ((Leaf*)(node->left))->index + 1;
if (val > maxxor || (val == maxxor && i == maxend && start > maxstart))
{
maxxor = val;
maxstart = start, maxend = i;
}
}
node = root;
for (int b = 21; b >= 0; --b)
{
if (xors & (1 << b))
{
if (node->right == NULL)
{
node->right = new Tree();
}
node = node->right;
}
else
{
if (node->left == NULL)
{
node->left = new Tree();
}
node = node->left;
}
}
if (node->left == NULL)
{
node->left = new Leaf(i);
}
else
{
((Leaf*)(node->left))->index = i;
}
}
fin.close();
ofstream fout("cowxor.out");
fout << maxxor << " " << maxstart + 1 << " " << maxend + 1 << endl;
fout.close();
return 0;
}