排列问题–算法竞赛经典习题:用123456789组成3个三位数,abc,def和ghi,每个数字恰好使用一次,要求abc:def:ghi=1:2:3。按照“abc def ghi”的格式输出所有解。(C++实现)
按照此题,先要有思路:
1.解决三个三位数问题,先要求解出来对应的个位数、十位数和百位数。
2.对应的个位数、十位数和百位数需要做判断,不能出现重复的数字
3.最后,实现暴力求解,查找符合要求的三位数,并输出。
按照上面的思路,我们可以得到对应的函数实现其功能,话不多说,先上代码:
#include <iostream>
#include <iomanip>
using namespace std;
int x1, x2, x3, y1, y2, y3, z1, z2, z3;
//全局变量定义,其实为了好区分,分别为三个三位数的对应数字
void quwei(int &x1, int &x2, int &x3, int x) //这个函数实现求解对应位数的数字出来
{
x3 = x % 10;
x2 = ((x - x3) / 10) % 10;
x1 = ((x - x3 - 10 * x2) / 100) % 10;
}
/*对循环的数字进行判断*/
int* shuzu(int x1, int x2, int x3, int b[9])
{
for (int i = 0; i < 9; i++) {
if (x1 == b[i])
b[i] = 0;
}
for (int i = 0; i < 9; i++) {
if (x2 == b[i])
b[i] = 0;
}
//printf("===%d===\n",x2);
for (int i = 0; i < 9; i++) {
if (x3 == b[i])
b[i] = 0;
}
return b;
}
int pan(int x, int y, int z) {
int b[9] = { 1,2,3,4,5,6,7,8,9 };
int t = 0;
quwei(x1, x2, x3, x); quwei(y1, y2, y3, y); quwei(z1, z2, z3, z);
shuzu(x1, x2, x3, b); shuzu(y1, y2, y3, b); shuzu(z1, z2, z3, b);
for (int i = 0; i < 9; i++)
{
if (b[i] == 0)
t++;//对0计数
}
if (t == 9)//若b[]中的0为九个则说明123456789都被用到,则满足题意返回1
return 1;
else return 0;
}
int main()
{
int x,y,z;
for (x = 123; x<398; x++)
{
y = 2 * x;
z = 3 * x;
if (z < 987 && (x % 10 != 0) && (y % 10 != 0) && (z % 10 != 0))
// x和y和z % 10 != 0意思是个位数不能含有0
if (pan(x, y, z))
cout << x <<" " << y<<" " << z << endl;
}
return 0;
}
上面可以看出来,是以面向对象的思想来求解这个题目了,分别以对应的功能设置函数来求解。
但是,实际运行的时候有问题!!!
后面仔细一查,发现是这样的:
原来这个y1在math.h里定义过了。有点神奇,居然写了个这么常用的命名方式做它的函数名。
继续打开math.h - corecrt_math.h ,让我来看看到底是哪个神奇函数在作怪,
然后你会发现,不仅是y1,连j0,j1,jn,y0,yn都被定义了。
不过没事,我们只要符合相关的命名规则,不与math.h里面的函数名重名就好了,对上面的y1实现改名就OK。
运行成功的代码如下:
#include <iostream>
#include <iomanip>
using namespace std;
int x1, x2, x3, n1, y2, y3, z1, z2, z3;
//全局变量定义,其实为了好区分,分别为三个三位数的对应数字
void quwei(int &x1, int &x2, int &x3, int x)//这个函数实现求解对应位数的数字出来
{
x3 = x % 10;
x2 = ((x - x3) / 10) % 10;
x1 = ((x - x3 - 10 * x2) / 100) % 10;
}
/*对循环的数字进行判断*/
int* shuzu(int x1, int x2, int x3, int b[9])
{
for (int i = 0; i < 9; i++) {
if (x1 == b[i])
b[i] = 0;
}
for (int i = 0; i < 9; i++) {
if (x2 == b[i])
b[i] = 0;
}
//printf("===%d===\n",x2);
for (int i = 0; i < 9; i++) {
if (x3 == b[i])
b[i] = 0;
}
return b;
}
int pan(int x, int y, int z) {
int b[9] = { 1,2,3,4,5,6,7,8,9 };
int t = 0;
quwei(x1, x2, x3, x); quwei(n1, y2, y3, y); quwei(z1, z2, z3, z);
shuzu(x1, x2, x3, b); shuzu(n1, y2, y3, b); shuzu(z1, z2, z3, b);
for (int i = 0; i < 9; i++)
{
if (b[i] == 0)
t++;//对0计数
}
if (t == 9)//若b[]中的0为九个则说明123456789都被用到,则满足题意返回1
return 1;
else return 0;
}
int main()
{
int x,y,z;
for (x = 123; x<398; x++)
{
y = 2 * x;
z = 3 * x;
if (z < 987 && (x % 10 != 0) && (y % 10 != 0) && (z % 10 != 0))
//x和y和z % 10 != 0意思是个位数不能含有0
if (pan(x, y, z))
cout << x <<" " << y<<" " << z << endl;
}
return 0;
}
运行结果,如下:
参考:
算法竞赛经典入门(第2版)–清华大学出版社
Standard library header < math >
These are some more exotic mathematical functions .