算法提高 连接乘积
时间限制: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的全排列
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
192384576
思路分析:推测范围大小,暴力解决,详情看代码。
#include <cstdio>
#include <string>
#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;
vector<string> ans;
string s[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
string intToString( int n ) {
string ans;
while( n ) {
ans = ans + s[n % 10];
n = n / 10;
}
reverse( ans.begin(), ans.end() );
return ans;
}
bool check( string str ) {
int visit[10] = { 0 };
for( int i = 0; i < str.size(); i++ ) {
visit[str[i] - '0']++;
}
if( visit[0] > 0 ) return false;
for( int i = 1; i < 10; i++ ) {
if( visit[i] != 1 ) {
//printf( "%d Error\n", i );
return false;
}
}
return true;
}
int main() {
// i < 9999也行,999不行
for( int i = 1; i < 99999; i++ ) {
string str;
for( int j = 1; j < 10; j++ ) {
str = str + intToString( i * j );
if( check( str ) ) {
ans.push_back( str );
//cout << str << endl;
break;
}
}
}
sort( ans.begin(), ans.end() );
for( int i = 0; i < ans.size(); i++ ) {
cout << ans[i] << endl;
}
return 0;
}