牛客网暑期ACM多校训练营(第七场)A Minimum Cost Perfect Matching 详解 (对位运算&的理解)

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

Minimum Cost Perfect Matching

时间限制: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.

示例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.

题意:在图的左边给你一个从0到n-1个数的数列,您的任务是从右边的【0,n-1】中找到图的最小代价完美匹配,即左边的每个数与右边的一个一个数恰好匹配。匹配的成本是图中 两两& 的成本的总和。要使最终匹配成本最小,最后输右边的序列。

思路:

写出【0,16】每个数的二进制;

可以发现 从n到0都可以找到一对数两两&为0;(i,j),i  !=  j  &&(  i <= n  ,   j  <=  n),即无论n为多大 最终成本一定为0;

从n-1出发,找到第一个  i  可以与(n-1&i==0) 的数,比如n=17,第一个i为15:1111 与 16:10000, 16&15=0,随后再接着找到第一个  i  可以与(14&i==0) 的数,即 i=1,随后,的配对就是(14,1)(13,2)(12,3)……最后0与0配对就是答案

PS:(不懂得对照【0,16】的二进制表);

AC代码:

#include<bits/stdc++.h>
using namespace std;
int ans[500005];
int solve(int x)
{
  int y=x,rec;
  for(int i=x; i>=0; i--)
    if((i&x)==0)//第一个i i&n-1 刚好为0 比如 x=10:1010 则i=5:101
                                // x=13: 1101  则 i=2:10 两者&为0;
    {
      rec=i;
      for(int j=i; j<=x; j++,y--)//一一对应 j&y 也为0
        ans[j]=y;
      break;
    }
  printf("%d\n",rec);
  return rec;
}
int main()
{
  int nn,n;
  scanf("%d",&nn);
  n=nn-1;
  ans[0]=0;
  while(n>0)//还没对应完所有数  //重新找对应
  {
    n=solve(n)-1;
  }
  for(int i=0; i<nn-1; i++)
    printf("%d ",ans[i]);
  printf("%d\n",ans[nn-1]);
  return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41668093/article/details/81544032