题目链接:http://codeforces.com/contest/280/problem/B
题目大意:
给定一个由n个数组成的一个序列,s[l..r] (1 ≤ l < r ≤ n)代表原序列中从第l个到第r个组成的子序列,对于每一个这样的序列,都有一个幸运数字,其值为序列中最大的2个数字异或的值,求所有这些幸运数字中最大的是多少。
分析:
假定所有数都可以用k位二进制位表示,不妨设所有数的第k位二进制位不全相同(全相同就可以一起去掉,对答案没影响),那么取得最优解的s[l..r]中一定有且只有一个数,其第k位二进制位为1,其余数的第k位二进制位都为0。
用第k位二进制位的值来表示s数组中的数,大致可表示为:000100000111000110,那么取得最优解的s[l..r]一定是从其中某个1开始,向左或者向右包含几个数值为0的数,只要全部遍历一遍即可,时间复杂度为O(n)。
代码如下:
1 #include <bits/stdc++.h> 2 using namespace std; 3 4 #define rep(i,n) for (int i = 0; i < (n); ++i) 5 #define For(i,s,t) for (int i = (s); i <= (t); ++i) 6 #define rFor(i,t,s) for (int i = (t); i >= (s); --i) 7 #define foreach(i,c) for (__typeof(c.begin()) i = c.begin(); i != c.end(); ++i) 8 #define rforeach(i,c) for (__typeof(c.rbegin()) i = c.rbegin(); i != c.rend(); ++i) 9 10 #define pr(x) cout << #x << " = " << x << " " 11 #define prln(x) cout << #x << " = " << x << endl 12 13 #define LOWBIT(x) ((x)&(-x)) 14 15 #define ALL(x) x.begin(),x.end() 16 #define INS(x) inserter(x,x.begin()) 17 18 #define ms0(a) memset(a,0,sizeof(a)) 19 #define msI(a) memset(a,inf,sizeof(a)) 20 #define msM(a) memset(a,-1,sizeof(a)) 21 22 #define pii pair<int,int> 23 #define piii pair<pair<int,int>,int> 24 #define mp make_pair 25 #define pb push_back 26 #define fi first 27 #define se second 28 29 inline int gc(){ 30 static const int BUF = 1e7; 31 static char buf[BUF], *bg = buf + BUF, *ed = bg; 32 33 if(bg == ed) fread(bg = buf, 1, BUF, stdin); 34 return *bg++; 35 } 36 37 inline int ri(){ 38 int x = 0, f = 1, c = gc(); 39 for(; c<48||c>57; f = c=='-'?-1:f, c=gc()); 40 for(; c>47&&c<58; x = x*10 + c - 48, c=gc()); 41 return x*f; 42 } 43 44 typedef long long LL; 45 typedef unsigned long long uLL; 46 const int inf = 1e9 + 9; 47 const LL mod = 1e9 + 7; 48 const int maxN = 1e5 + 7; 49 50 int n; 51 int s[maxN]; 52 int ans[maxN]; 53 54 int main(){ 55 while(cin >> n) { 56 // highBit最高二进制差异位,比如{101100, 101101, 101011, 101010}, 57 // 那么highBit = 000100,因为4个数有共同的高3位101,到第四位不同 58 int max_1 = -1, min_1 = inf, highBit = 0; 59 int ans = -1; 60 For(i, 1, n) { 61 cin >> s[i]; 62 highBit |= s[i]; 63 max_1 = max(max_1, s[i]); 64 min_1 = min(min_1, s[i]); 65 } 66 67 while(highBit & ~LOWBIT(highBit)) highBit &= ~LOWBIT(highBit); 68 69 while(!((max_1 & highBit) ^ (min_1 & highBit))) { 70 max_1 &= ~highBit; 71 min_1 &= ~highBit; 72 highBit >>= 1; 73 } 74 75 For(i, 1, n) { 76 if(s[i] & highBit) { 77 int tmp_max = -1; 78 For(j, i + 1, n) { 79 if(s[j] & highBit) { 80 i = j - 1; 81 break; 82 } 83 tmp_max = max(tmp_max, s[j]); 84 ans = max(ans, tmp_max ^ s[i]); 85 } 86 } 87 } 88 rFor(i, n, 1) { 89 if(s[i] & highBit) { 90 int tmp_max = -1; 91 rFor(j, i - 1, 1) { 92 if(s[j] & highBit) { 93 i = j + 1; 94 break; 95 } 96 tmp_max = max(tmp_max, s[j]); 97 ans = max(ans, tmp_max ^ s[i]); 98 } 99 } 100 } 101 102 cout << ans <<endl; 103 } 104 return 0; 105 }