【 Polo the Penguin and XOR operation 】【CodeForces - 288C】(思维)

版权声明:本人原创,未经许可,不得转载 https://blog.csdn.net/qq_42505741/article/details/84404795

题目:

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

4

Output

20
0 2 1 4 3

解题报告:思维题目,之前一开始就走错了方向,自己找错了结论,以为就是讨论n的奇偶性,若是n为奇数的话,就可以和0异或,之间的相邻的两位奇偶进行异或,若n为偶数的话,直接排除0的干扰,从1-n之间奇偶进行异或,确实是在小范围的测试样例是可以正确实现的。其实最终的正确的解法是:先找到最大的全一数字,然后寻找合适的进行,最大异或,然后逐次寻找进行最优判断,直到全部进行完毕。

ac代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
#define mod 1000000007

const int maxn =1e7+100;
ll num[maxn];
int main()
{
	ll n;
	while(scanf("%lld",&n)!=EOF)
	{
		ll t=1;
		while(t<=n)
			t*=2;
		t--;
		memset(num,-1,sizeof(num));
		for(int i=n;i>=0;i--)
		{
			if(num[i]!=-1)
				continue;
			else
			{
				while((t^i)>n||num[t^i]!=-1)
					t/=2;//出界
				num[i]=t^i;
				num[t^i]=i;//交换,最优交换。
			}
		}
		ll sum=0;
		for(int i=0;i<=n;i++)
			sum+=(i^num[i]);
		printf("%lld\n",sum);
		for(int i=0;i<n;i++)
			printf("%lld ",num[i]);
		printf("%d\n",num[n]);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42505741/article/details/84404795