题目链接:https://ac.nowcoder.com/acm/contest/317/C
思路1:直接bfs。
#include<bits/stdc++.h>
using namespace std;
const int N = 3e3+100;
const int M = 5000;
int p[N], vis[M], n;
queue <int> q;
int bfs()
{
q.push(p[1]); vis[p[1]] = 1;
int ans = -1;
while(!q.empty())
{
int now = q.front();
q.pop();
for(int i = 2; i <= n; i++)
{
if(now > p[i])
{
int nex = p[i] ^ now;
if(i == n && ans < nex) ans = nex;
if(!vis[nex] && i != n)
{
q.push(nex);
vis[nex] = 1;
}
}
}
}
return ans;
}
int main()
{
scanf("%d",&n);
for(int i = 1; i <= n; i++)
scanf("%d",&p[i]);
printf("%d\n",bfs());
}
思路2:因为异或满足交换律,所以我们暴力枚举每一种情况,然后找一个最大值。
#include<bits/stdc++.h>
using namespace std;
const int N = 3e3+100;
const int M = 5000;
int dp[M] = {0}, p[N], a[N];
vector <int> v;
int main()
{
int n, ans = -1;
scanf("%d",&n);
for(int i = 1; i <= n; i++)
scanf("%d",&p[i]);
for(int i = 2; i <= n-1; i++)
if(p[1] > p[i] && p[i] > p[n])
v.push_back(p[i]);
dp[p[1]^p[n]] = 1;
for(auto x : v)
for(int j = M; j >= 0; j--)
if(dp[j] == 1) dp[j^x] = 1;
for(int i = M; i >= 1; i--)
if(dp[i]) {ans = i; break; }
printf("%d\n",ans);
}