题目:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=2531
A traveller plans a round trip through n cities, where n is a power of 2, in which case we simply indexthem with numeric values from 0 to n - 1. The traveller lives in one of them, and that's where hewill start and end his trip. He only visits each city once, and for some particular reason the twoadjacent cities on his trip should satify an equation that (A xor B) is also a power of 2.
For his odd mind no travel agency is willing to offer any help and finally he comes to you for a solution.You would either tell him it's not possible to arrange a trip for him.
Input
Input has two integers n and m, which are respectively the number of cities and the city he lives in.
Proceed through multiple cases until you meet a case n = 0.
Output
Print "NO" or a list of n city numbers on a single line separated by a single space.
Sample Input2 1 4 0 0 0Sample Output
1 0 0 1 3 2分析:xor的意思是异或。在《C语言精选名题精选百则》中读过有关格雷码的问题,只是有个印象,没想到在这里居然又遇上了。开始只是用单纯的暴搜。。
#include <iostream> #include <cstdio> #include <cmath> #include <cstring> using namespace std; const int maxn=1e6; bool tag[maxn]; int que[maxn],q1,q2; void dfs(int s){ if(tag[s]) return ; tag[s]=1; que[q2++]=s; int length=log2(double(s)); for(int i=0;i<=length;i++){ int res=s^(1<<i); dfs(res); } } bool check(int n){ bool ok=1; for(int i=0;i<n;i++)if(tag[i]==0) ok=0; return ok; } int main() { //freopen("cin.txt","r",stdin); int n,m; while(cin>>n>>m&&n){ int length=log2(double(n)); for(int i=0;i<=length;i++){ memset(tag,0,sizeof(tag)); tag[m]=1; q1=q2=0; que[q2++]=m; int res=m^(1<<i); dfs(res); if(check(n)){ for(;q1<q2-1;q1++) printf("%d ",que[q1]); printf("%d\n",que[q1]); break; } } } return 0;
十进制数 |
自然二进制数 |
格雷码 |
十进制数 |
自然二进制数 |
格雷码 |
0 |
0000 |
0000 |
8 |
1000 |
1100 |
1 |
0001 |
0001 |
9 |
1001 |
1101 |
2 |
0010 |
0011 |
10 |
1010 |
1111 |
3 |
0011 |
0010 |
11 |
1011 |
1110 |
4 |
0100 |
0110 |
12 |
1100 |
1010 |
5 |
0101 |
0111 |
13 |
1101 |
1011 |
6 |
0110 |
0101 |
14 |
1110 |
1001 |
7 |
0111 |
0100 |
15 |
1111 |
1000 |
#include <iostream> using namespace std; int fac[100],top; void turn(int x) { top=0; while(x){ fac[top++]=x%2; x/=2; } for(int i=top-1;i>=0;i--) cout<<fac[i]; cout<<endl; } int toGray ( int x ) { return x ^ ( x >> 1 ); } /* int GraytoDecimal ( int x ) { int y = x; while ( x >>= 1 ) y ^= x; return y; } */ int main() { int n, m; while ( 1 ) { cin >> n >> m; if ( n == 0 ) break; for ( int i = 0; i < n - 1; i++ ) { cout << toGray ( (i+m) % n ) << ' '; //turn(DecimaltoGray ( (i+m) % n )); } cout << toGray ( (n-1+m) % n ) << ' '; //turn(DecimaltoGray ( (n-1+m) % n )); } return 0; }