牛客网暑期ACM多校训练营(第七场)A-Minimum Cost Perfect Matching

本文介绍了牛客网暑期ACM多校训练营中的一道题目,涉及完全二分图和位运算。题目要求找到一个最小成本完美匹配,其中边的权重为两个节点编号的按位与。解决方案是通过位操作找到合适的配对,以使数字与位置按位与的结果最小。
摘要由CSDN通过智能技术生成

链接: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.

题意:给定一个n,将0到n-1,安排位置,使得数字和安排后的所在位相与,和最小

思路:纸上推了一波,都写成二进制,你会发现正好可以插空配对,比如8(1000),7(111),与为0,然后规律就是,你直接把自己按位取反,就是恰当的位置

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <vector>
#include <cmath>

using namespace std;

#define inf 0x3f3f3f3f

const int maxn=5e5+7;

int data[maxn];

int main()
{
    int n;
    scanf("%d",&n);
    for (int i = n-1; i >= 0 ; --i)
    {
        for (int j = 19; j >= 1 ; --j)
        {
            int flag= ( 1 << j ) - 1;
            if ((flag ^ i) < n && data[flag ^ i] == 0)
            {
                data[flag^i]=i;
                break;
            }
        }
    }
    for (int i = 0; i < n ; ++i)
    {
        printf("%d",data[i]);
        if(i==n-1) printf("\n");
        else printf(" ");
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值