用1,2,3,…,9组成3个三位数abc,def和ghi,每个数字恰好使用一次,要 求abc:def:ghi=1:2:3。按照“abc def ghi”的格式输出所有解,每行一个解。

思路:注意到ghi是abc的三倍,所以abc的范围就是123到329之间,故而遍历[123,329]中的所有整数,然后每个整数算出对应的def和ghi,然后可以建立一个hash表,将abcdefghi存入其中(比如位置即该位的数值),如果出现冲突,说明一个数字用了两边,舍弃该条件;否则,可以输出答案。

C语言实现如下:

#include<stdio.h>
#include<math.h>
#include<time.h>
#include<string.h>
int main()
{
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
	
	for(int abc = 123; abc <= 329; abc++){
		int def = abc * 2;
		int ghi = abc * 3;
		int arr[11];
		memset(arr, 0, sizeof(arr));
		unsigned int total = abc * 1e6 + def * 1e3 + ghi;
		int i;
		for (i = 0; i < 9; i++){
			//get the i'th position
			unsigned int temp = total;
			for (int j = 0; j < i; j++){
				temp /= 10;
			}
			temp = temp % 10;
			//hash
			if (!temp || arr[temp]) break;
			else 
				arr[temp] = temp;
		} 
		if (i == 9) {
			printf("%d %d %d\n", abc, def, ghi);
		}
	}
	
	printf("Total time cost: %.2fs\n",(double)clock()/CLOCKS_PER_SEC);
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/chineseyjh/article/details/80932283