当前位置: 代码迷 >> 综合 >> 牛客网多校练习赛7 A Minimum Cost Perfect Matching (数学规律+位运算)
  详细解决方案

牛客网多校练习赛7 A Minimum Cost Perfect Matching (数学规律+位运算)

热度:42   发布时间:2023-11-15 16:29:52.0

链接:https://www.nowcoder.com/acm/contest/145/A
来源:牛客网
 

题目描述

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.

示例1

输入

复制

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.
#include<iostream>
#include<algorithm>
#include<string>
#include<map>//int dx[4]={0,0,-1,1};int dy[4]={-1,1,0,0};
#include<queue>//int gcd(int a,int b){return b?gcd(b,a%b):a;}
#include<vector>
#include<cmath>
#include<stack>
#include<string.h>
#include<stdlib.h>
#include<cstdio>
#define mod 1e9+7
#define ll unsigned long long
#define MAX 1000000000
#define ms memset
#define maxn 500005
using namespace std;int vis[maxn],idex[maxn];
int n;
int compute(int x)
{int cnt=1;while(cnt<=x)  cnt*=2;return x^(cnt-1);
}
/*
题目大意:给定一个n,要求0到n-1中,
的完全匹配代价最小的序列。(就是把0到n-1重拍然后使得对应位置和数相and均为零)。从大到小遍历,(不能从小到大,因为零可能对应1,或者111等等)。
对每个数按位取反(用全为1的数异或即可,详见代码),
然后标记每个位置,类似筛法的思想,标过的不用再标记,然后继续遍历下去。
*/int main()
{scanf("%d",&n);    n--;memset(idex,0xff,sizeof(idex));for(int i=n;i>=0;i--){int sta=compute(i);if(idex[i]!=-1) continue;idex[sta]=i , idex[i]=sta;}for(int i=0;i<=n;i++) printf("%d%c",idex[i],i==n?'\n':' ');return 0;
}

 

  相关解决方案