题解:AND Sorting

CF1682B

Posted by TH911 on August 8, 2025

题目传送门

第一发橙题题解。

记位运算 & 为 $\&$。

$T$ 次询问,每次询问给出的序列都是 $0\sim n-1$ 的排列。记排列为 $a_1,a_2,a_3,\cdots,a_{n-1}$。

本题所具有核心性质便是:所有需要更改位置的数均进行了一次 $\&$ 操作。

也就是说,所有这些满足 $a_i\neq i-1$ 的 $a_i$ 都包含了 $X$,即 $a_i\& X=X$。

$X$ 一定在排列 $a$ 中。因为对于任意的非负整数 $x,y$,有 $0\leq x\& y\leq x,y$。故有 $0\leq X\leq n-1$,$X$ 在排列 $a$ 中。

依次构造排序方案也是简单的,交换 $a,b$ 时:

  1. 交换 $a,X$。
  2. 交换 $b,X$。
  3. 交换 $a,X$。

答案 $X$ 为:

\[X=\operatorname*{\&}_{a_i\neq i-1}a_i\]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
//#include<bits/stdc++.h>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<iomanip>
#include<cstdio>
#include<string>
#include<vector>
#include<cmath>
#include<ctime>
#include<deque>
#include<queue>
#include<stack>
#include<list>
using namespace std;
constexpr const int N=2e5;
int n,a[N+1];
int main(){
	/*freopen("test.in","r",stdin);
	freopen("test.out","w",stdout);*/
	
	ios::sync_with_stdio(false);
	cin.tie(0);cout.tie(0);
	
	int T;
	cin>>T;
	while(T--){
		cin>>n;
		for(int i=1;i<=n;i++){
			cin>>a[i];
		}
		//二进制位全为 1 
		int ans=(1<<(int)ceil(log2(n-1)))-1;
		for(int i=1;i<=n;i++){
			if(a[i]==i-1){
				continue;
			}
			ans&=a[i];
		}
		cout<<ans<<'\n';
	} 
	
	cout.flush();
	 
	/*fclose(stdin);
	fclose(stdout);*/
	return 0;
}