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

链接: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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值