1. 程式人生 > >【 Polo the Penguin and XOR operation 】【CodeForces - 288C】(思維)

【 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 x

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