Jilin University Superstar Range Assignment 08Debruijn Problem

Title: Debruijn problem

Title description:

As shown in the figure, a ring is formed by 2^3 binary digits 0 and 1. Make 2^3 3-bit binary numbers exactly once in the ring. The order currently shown in the figure is: 0, 1, 2, 5, 3, 7, 6, 4. Design a program to generate such a ring. The ring is composed of 2^n binary numbers, which happen to contain 2^n different n-bit binary numbers.
Figure

Input: n (n<=4)

Output: Output matching answers in lexicographic order (when there are multiple sets of essentially different solutions, only the smallest sequence in lexicographic order is output); each line of numbers is separated by a Western space, and there is a newline at the end of the line.

Example 1:

Input:
3
Output:
0 0 0 1 0 1 1 1

#include<stdio.h>
#include<stdlib.h>
int num, a[16] = {
    
     0}, N;
int twodeNcifang(int N) {
    
    //2的n次方
	int res = 1;
	for (int i = 0; i < N; i++)
		res = res * 2;
	return res;
}
int check(int* a) {
    
    //检查当前数组是1否0符合条件
	for (int i = 0; i < twodeNcifang(N) - (N - 1); i++)
		for (int j = i + 1; j < twodeNcifang(N); j++) {
    
    
			int f = 0;
			for (int k = 0; k < N; k++) {
    
    
				int r = j + k;
				if (r > twodeNcifang(N) - 1)
					r = r - twodeNcifang(N);
				if (a[i + k] != a[r]) 
					f = 1;
			}
			if (f == 0)
				return 0;
		}
	return 1;
}
void DFS(int* a, int n, int N) {
    
    
	if (n <= twodeNcifang(N)) {
    
    
		if (n == twodeNcifang(N))
			if (check(a)) {
    
    
				printf("%d", a[0]);
				for (int i = 1; i < twodeNcifang(N); i++)
					printf(" %d", a[i]);
				printf("\n");
				exit(0);
			}
			else
				return;
		a[n] = 0;//试探
		DFS(a, n + 1, N);
		a[n] = 1;//退回
		DFS(a, n + 1, N);
	}
}
int main() {
    
    
	scanf("%d", &N);
	DFS(a, 0, N);
	for (int i = 0; i < twodeNcifang(N); i++)
		printf("%d", a[i]);
	return 0;
}

If there is a better solution or what can be improved, you can tell me in the comment area~

Guess you like

Origin blog.csdn.net/u010656213/article/details/111884279