算法竞赛入门经典(第二版) 习题2-6 排列(permutation)

page 35:

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


方法一
//思路:计算abc,def,ghi三个数中1-9每个数字的频数,如果至少有一个数字的频数不为1,就不符合条件。
#include
#include
#include
#include
#include
using namespace std;

int main()
{
    int abc,def,ghi,i;
    int a[10];
    memset(a,0,sizeof(a));
    for(abc=123;abc<=987/3;abc++)
    {
        def=2*abc;
        ghi=3*abc;
        a[abc/100]++;
        a[abc/10%10]++;
        a[abc%10]++;
        a[def/100]++;
        a[def/10%10]++;
        a[def%10]++;
        a[ghi/100]++;
        a[ghi/10%10]++;
        a[ghi%10]++;
        for(i=1;i<10;i++)
            if(a[i]!=1) break;
        if(i==10) printf("%d %d %d\n",abc,def,ghi);
        memset(a,0,sizeof(a));
    }
    return 0;

方法二

//把频数数组换成标记数组,某个数字i出现过则置a[i]=1。如果不符合条件,必然至少有一个数组元素没有被标记。
#include 
#include 
#include 
int main()
{
    int abc,def,ghi,i;
    int a[10];

  memset(a, 0, sizeof(a));
  for(abc = 123; abc <= 329; abc++)
  {
     def = 2*abc;
     ghi = 3*abc;

     a[abc/100] = a[abc/10%10] = a[abc%10] = 1;
     a[def/100] = a[def/10%10] = a[def%10] = 1;
     a[ghi/100] = a[ghi/10%10] = a[ghi%10] = 1;

     for( i = 1; i <= 9; i++)
        if(a[i]==0) break;
     if(i==10) printf("%d %d %d\n", abc, def, ghi);
     memset(a, 0, sizeof(a));
  }
  return 0;
}



你可能感兴趣的:(基础题)