#include <stdio.h>
#include <math.h>
// 算法競賽的目標是編程對任意輸入均得到正確的結果。
// 請先獨立完成,如果有困難可以翻閱本書代碼倉庫中的答案,但一定要再次獨立完成。
// “抓住主要矛盾”——始終把學習、實驗的焦點集中在最有趣的部分。如果直觀地解決方案行得通,就不必追究其背后的原理。
/**
【題目】排列(permutation)
用1,2,3,…,9組成3個三位數abc,def和ghi,每個數字恰好使用一次,要
求abc:def:ghi=1:2:3。按照“abc def ghi”的格式輸出所有解,每行一個解。
*/
/**
【分析】思考了半天沒有思路,太難了。
*/
int main()
{
int abc,def,ghi;
int a[10],count=0;
memset(a,0,sizeof(a)); // 將a數組中的值全部設置為0
for (abc = 123;abc < 333;abc ++) { // 基本可以確定abc的最小值和最大值
def = 2 * abc;
ghi = 3 * abc;
// 設置數組中所有對應的9位數字位置的值1
a[abc/100] = 1; // a
a[abc/10%10] = 1; // b
a[abc%10] = 1; // c
a[def/100] = 1; // d
a[def/10%10] = 1; // e
a[def%10] = 1; // f
a[ghi/100] = 1; // g
a[ghi/10%10] = 1; // h
a[ghi%10] = 1; // i
int i;
for (i=1;i<=9;i++) {
count += a[i];
}
if (count == 9) {
printf("%d %d %d\n",abc,def,ghi);
}
// 重置count 和a數組
count = 0;
memset(a,0,sizeof(a));
}
return 0;
}
點評:這種整體的思路,以及縮小數字范圍的思路很牛逼。