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

题目:

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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值