算法提高 连接乘积
时间限制:1.0s 内存限制:256.0MB
问题描述
192这个数很厉害,用它分别乘以1、2、3,会得到:
192 x 1 = 192
192 x 2 = 384
192 x 3 = 576
把这三个乘积连起来,得到192384576,正好是一个1~9的全排列
我们把上面的运算定义为连接乘积:
m x (1 ... n) = k(其中m > 0 且 n > 1,对于上例,m = 192、n = 3、k = 192384576)
即k是把m分别乘以1到n的乘积连接起来得到的,则称k为m和n的连接乘积。
按字典序输出所有不同的连接乘积k,满足k是1~9的全排列
输出格式
每个k占一行
样例输出
显然,结果中应包含一行:
192384576
分析:对于某个m,其每一次乘法运算得到的积的位数以及对应的m的取值范围只可能满足:
1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 m = 1
1 + 2 + 2 + 2 + 2 5 <= m <= 9
2 + 2 + 2 + 3 25 <= m <= 32
3 + 3 + 3 123 <= m <= 329
4 + 5 5123 <= m <= 9876
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
long long int perm[30];
int n_perm;
void check(int min_m, int max_m, int max_n)
{
int k, is_valid;
for (int m = min_m; m <= max_m; ++m)
{
int appeared[10] = { 0 };
for (int n = 1; n <= max_n; ++n)
{
k = m * n;
while (k)
{
appeared[k % 10]++;
k /= 10;
}
}
is_valid = 1;
for (int i = 1; i <= 9; ++i)
{
if (appeared[i] != 1)
{
is_valid = 0;
break;
}
}
if (is_valid)
{
long long int output = 0;
for (int n = 1; n <= max_n; ++n)
{
k = m * n;
output = output * (int)pow(10, (int)log10(k) + 1) + k;
}
perm[n_perm++] = output;
}
}
}
int cmp(const void *a, const void *b)
{
if (*(long long int*)a - *(long long int*)b < 0)
return -1;
if (*(long long int*)a - *(long long int*)b > 0)
return 1;
return 0;
}
int main()
{
n_perm = 0;
check(1, 1, 9);
check(5, 9, 5);
check(25, 32, 4);
check(123, 329, 3);
check(5123, 9876, 2);
qsort(perm, n_perm, sizeof(long long int), cmp);
for (int i = 0; i < n_perm; ++i)
printf("%lld\n", perm[i]);
return 0;
}