UVA 12447-两个二进制只有一位不一样


D - Pieces and Bits
Time Limit:1000MS     Memory Limit:0KB     64bit IO Format:%lld & %llu
Submit  Status  Practice  UVA 12447

Description

Problem D: Pieces and Bits

Given an even integer N, print a sequence of 2^N different N-bit binary numbers in such way that every element of the sequence (except the first one) has exactly one bit the same as the previous one (e.g. 0001 and 1111)

Input Format

The input starts with an integer T - the number of test cases (T <= 8). T cases follow on each subsequent line, each of them containing the integer N (2 <= N <= 16).

Output Format

For each test case, print a sequence that satisfies the stated condition, one integer per line. Any valid sequence will be accepted.

Sample Input

1
2

Sample Output

0
1
3
2
(The sequence in the sample output in binary is {00,01,11,10})


求(1<<n)个二进制数和前面的只有一位不一样



自己写的代码:

#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <math.h>
#include <set>
#include <map>
#include <string>
#include <string.h>

using namespace std;

int a[55];
int b[55];
int n;
int ans = 0;

void init () {
	memset (a, 0, sizeof (a));
	memset (b, 0, sizeof (b));
}

void change_to_twobinary (int x) {
	int k = 0;
	for (int j = 0; j < n; j++) {
		a[k++] = x % 2;
		x >>= 1;
	} 
}

int get_to_twobinary () {
	int ans = 0;
	for (int j = 0; j < n ; j ++) {
		ans = 2 * ans + b[j] ;
	}
	return ans;
}

int main() {
	int cas;
	scanf ("%d", &cas);
	while (cas--) {
		scanf ("%d", &n);
		int num = (1 << n);
		for (int i = 0; i < num; i++) {
			init ();
			int flag = i ;
			change_to_twobinary(flag);
			b[n - 1] = a[n - 1];
			for (int j = n - 2; j >= 0; j--) {
				if (a[j] != a[j + 1])  b[j] = 1;
				else  b[j] = 0;
			}
			if (!(i % 2)) {
				for (int j = 0; j < n; j++) {
					if (b[j] == 0) b[j] = 1;
					else b[j] = 0;
				}
			}
			printf("%d\n" , get_to_twobinary());
		}
	}
	return 0;
}

写的有点麻烦,没有直接简单的处理:

#include <iostream>
#include <cstdio>
using namespace std;

int N;

void solve() {
	N = 1 << N;
	for (int i = 0; i < N; i++) {
		if (i & 1) {
			int a = i >> 1;
			int b = i;
			int c = a ^ b;
			printf("%d\n", c ^ (N - 1));
		} else { 
			int a = i >> 1;
			int b = i;
			int c = a ^ b;
			printf("%d\n", c);
		}
	}
}

int main() {
	int T;
	scanf("%d", &T);
	while (T-- > 0) {
		scanf("%d", &N);
		solve();
	}
	return 0;
}


你可能感兴趣的:(UVA 12447-两个二进制只有一位不一样)