Zoj 2531 traveller (Gray code)

Source: Internet
Author: User


Time Limit: 2 seconds memory limit: 65536 kb Special Judge

A traveller plans a round trip through N cities, where n is a power of 2, in which case we simply index them with numeric values from 0 to n-1. the traveller lives in one of them, and
That's where he will start and end his trip. he only visits each city once, and for some special reason the two adjacent cities on his trip shoshould 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 wocould either tell him it's not possible to arrange a trip for him.


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.


Print "no" or a list of N city numbers on a single line separated by a single space.

Sample Input

2 14 00 0

Sample output

1 00 1 3 2
#include <iostream>using namespace std;int DecimaltoGray ( 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 << DecimaltoGray ( (i+m) % n ) << ' ';        cout << DecimaltoGray ( (n-1+m) % n ) << endl;    }    return 0;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.