用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;
} 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值