【CodeForces - 289E 】Polo the Penguin and XOR operation (数学,异或,贪心)
題干:
Little penguin Polo likes permutations. But most of all he likes permutations of integers from?0?to?n, inclusive.
For permutation?p?=?p0,?p1,?...,?pn, Polo has defined its beauty — number?.
Expression??means applying the operation of bitwise excluding "OR" to numbers?xand?y. This operation exists in all modern programming languages, for example, in language?C++?and?Java?it is represented as "^" and in?Pascal?— as "xor".
Help him find among all permutations of integers from?0?to?n?the permutation with the maximum beauty.
Input
The single line contains a positive integer?n?(1?≤?n?≤?106).
Output
In the first line print integer?m?the maximum possible beauty. In the second line print any permutation of integers from?0?to?n?with the beauty equal to?m.
If there are several suitable permutations, you are allowed to print any of them.
Examples
Input
4Output
20 0 2 1 4 3題目大意:
? ?給n個數,分成兩組A和B,A中的可以找B中的連線,求最優匹配,權值為二者的異或值。(
解題報告:
? 我把題目大意搞得跟二分圖一樣,,,但是其實不是的。。只是方便理解(看數據量也知道不是)
? 可以證明,一定對于每一個數都找到一個對應的匹配
Since we need to maximize the result, we need to find such permutation, for which the least number of bit disappear. (We consider bit disappeared if it was 1 both in?i?and?pi, so in??it is 0). It turns out that for each?n?there is such permutation that no bit disappear. How to build it? We will be solving problem by iterations while?n?>?0. On each iteration, we need to find the biggest (the leftmost in binary representation) bit which is not?0?in binary representation of?n?and denote it position (bits are numbered from 0) by?b. Now we need to find integer?m?— minimal integer from?0?to?n, inclusive, such that?b-th bit is also?1?in it. After that you can see (look image below), that at??no bit disappear, at??no bit disappear, ..., at??no bit disappear. So, it is good to assign exactly that integers to our permutation, i. e.?pm?=?m?-?1?and?pm?-?1?=?m,?pm?+?1?=?m?-?2?and?pm?-?2?=?m?+?1?and so on. After that assign value?m?-?(n?-?m?+?1)?-?1?to?n?and go to next iteration.
Now when we know how to build permutation and that no bit disappear, the value of the answer is equal to?.
AC代碼:
#include<cstdio> #include<iostream> #include<algorithm> #include<queue> #include<map> #include<vector> #include<set> #include<string> #include<cmath> #include<cstring> #define ll long long using namespace std; const int MAX=1e6 + 5; int ans[MAX]; ll sum=0,x=1; int main() {int n;cin >>n;while(x<=n) x<<=1;x--; for(int i=n; i>=0; i--) {if(ans[i]!=0) continue;while((x^i)>n||ans[x^i]!=0) x>>=1;ans[x^i]=i;ans[i]=x^i;}sum=0;for(int i=0; i<=n; i++)sum+=i^ans[i];cout <<sum<<endl;for(int i=0; i<=n; i++) {printf("%d%c",ans[i],i == n ? '\n' : ' ');}return 0; }?
總結
以上是生活随笔為你收集整理的【CodeForces - 289E 】Polo the Penguin and XOR operation (数学,异或,贪心)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 昔日安卓大哥HTC发布元宇宙新机Desi
- 下一篇: SUV坠落百米悬崖3人幸运生还!网友:日