牛客網多校練習賽7 A Minimum Cost Perfect Matching (數學規律+位運算)
阿新 • • 發佈:2019-01-24
題目描述
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.
輸入描述:
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; }