You are given a permutation pp of integers from 00 to n−1n−1 (each of them occurs exactly once). Initially, the permutation is not sorted (that is, pi>pi+1pi>pi+1 for at least one 1≤i≤n−11≤i≤n−1).
The permutation is called XX-sortable for some non-negative integer XX if it is possible to sort the permutation by performing the operation below some finite number of times:
- Choose two indices ii and jj (1≤i<j≤n)(1≤i<j≤n) such that pi&pj=Xpi&pj=X.
- Swap pipi and pjpj.
Here && denotes the bitwise AND operation.
Find the maximum value of XX such that pp is XX-sortable. It can be shown that there always exists some value of XX such that pp is XX-sortable.
Input
The input consists of multiple test cases. The first line contains a single integer tt (1≤t≤104)(1≤t≤104) — the number of test cases. Description of test cases follows.
The first line of each test case contains a single integer nn (2≤n≤2⋅105)(2≤n≤2⋅105) — the length of the permutation.
The second line of each test case contains nn integers p1,p2,...,pnp1,p2,...,pn (0≤pi≤n−10≤pi≤n−1, all pipi are distinct) — the elements of pp. It is guaranteed that pp is not sorted.
It is guaranteed that the sum of nn over all cases does not exceed 2⋅1052⋅105.
Output
For each test case output a single integer — the maximum value of XX such that pp is XX-sortable.
Example
input
Copy
4 4 0 1 3 2 2 1 0 7 0 1 2 3 5 6 4 5 0 3 2 1 4
output
Copy
2 0 4 1
思路:正确的位置不用换,因为正确的位置如果换了的话最后还得换回来,两遍&之后又回来了,所以我们找位置不正确的,因为最终都要与正确位置的数换,都要进行他与正确位置的按位与运算,所以我们只用找不正确位置的数和正确位置本身的数进行位运算的值然后和其他不正确位置的数和正确位置本身的数进行位运算的值进行位运算就好了。
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N=200000+10;
int n,x;
int a[N];
int con;
void sove(){
cin>>n;
int flag=-1;
for(int i=0;i<n;i++){
cin>>a[i];
if(a[i]!=i&&flag==-1){
con=a[i]&i;
flag=i;
}
}
for(int i=flag;i<n;i++){
if(a[i]!=i){
con=con&(a[i]&i);
}
}
cout<<con<<endl;
}
int main(){
int t;
cin>>t;
while(t--){
sove();
}
return 0;
}