首页 > 其他 > 详细

Minimum Cost Perfect Matching(牛客)

时间:2018-08-09 20:22:54      阅读:181      评论:0      收藏:0      [点我收藏+]

A、Minimum Cost Perfect Matching | 时间限制:1秒 | 内存限制:256M
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 <bits/stdc++.h>

using namespace std;

const int maxn = 5e5+5;

int main()
{
    int n;
    cin>>n;
    int now = n-1;
    int ans[maxn];
    while(1)
    {
        if(now<0)
            break;
        for(int i=now;i>=0;i--)
        {
            int t = i&now;
            if(t==0)
            {
                int cnt = (now-i+1)/2;
                for(int j=i,k=cnt;k>0;j++,k--)
                {
                    ans[j] = j+k*2-1;
                }
                for(int p=now,k=cnt;k>0;p--,k--)
                {
                    ans[p] = p-(k*2-1);
                }
                now = i-1;
                break;
            }
        }
    }
    for(int i=0;i<n;i++)
    {
        cout<<ans[i]<<" ";
    }
}

 

Minimum Cost Perfect Matching(牛客)

原文:https://www.cnblogs.com/hao-tian/p/9448736.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!