链接:https://www.nowcoder.com/acm/contest/145/A
来源:牛客网
时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 262144K,其他语言524288K
Special Judge, 64bit IO Format: %lld
题目描述
You have a complete bipartite graph where each part contains exactly n nodes, numbered from 0 to n - 1 inclusive.
The weight of the edge connecting two vertices with numbers x and y is (bitwise AND).
Your task is to find a minimum cost perfect matching of the graph, i.e. each vertex on the left side matches with exactly one vertex on the right side and vice versa. The cost of a matching is the sum of cost of the edges in the matching.
denotes the bitwise AND operator. If you're not familiar with it, see {https://en.wikipedia.org/wiki/Bitwise_operation#AND}.
输入描述:
The input contains a single integer n (1 ≤ n ≤ 5 * 105).
输出描述:
Output n space-separated integers, where the i-th integer denotes pi (0 ≤ pi ≤ n - 1, the number of the vertex in the right part that is matched with the vertex numbered i in the left part. All pi should be distinct. Your answer is correct if and only if it is a perfect matching of the graph with minimal cost. If there are multiple solutions, you may output any of them.
输入
3
输出
0 2 1
说明
For n = 3, p0 = 0, p1 = 2, p2 = 1 works. You can check that the total cost of this matching is 0, which is obviously minimal.
与运算,二进制找下规律
AC代码:
#include<bits/stdc++.h>
using namespace std;
int a[500010];
int get(int temp){
int j=1;
while(temp){
temp/=2;
j*=2;
}
return j-1;
}
int main(){
int n;
scanf("%d",&n);
if(n%2==1){
int num=get(n-1);
int up=n-1;
while(num){
int j=num-up;
int temp=num-up;
for(int i=up;i>=num-up;i--){
a[i]=j++;
}
num=get(num-up-1);
up=temp-1;
}
}
else{
a[n-1]=0;
a[0]=n-1;
int num=get(n-2);
int up=n-2;
while(num){
int j=num-up;
int temp=num-up;
for(int i=up;i>=num-up;i--){
a[i]=j++;
}
num=get(num-up-1);
up=temp-1;
}
}
for(int i=0;i<n-1;i++){
printf("%d ",a[i]);
}
printf("%d\n",a[n-1]);
}