题目:
题目描述
把 1~9 这9个数字分成两组,中间插入乘号,
有的时候,它们的乘积也只包含1~9这9个数字,而且每个数字只出现1次。
比如:
984672 * 351 = 345619872
98751 * 3462 = 341875962
9 * 87146325 = 784316925
…
符合这种规律的算式还有很多,请你计算在所有这些算式中,乘积最大是多少?
输出
输出一个整数表示答案
代码:
注意:乘积也必须是1-9各出现一次。
暴力全排列,等个几秒就出答案了
#include <iostream>
#include <algorithm>
#include <string>
#include <set>
using namespace std;
typedef long long ll;
ll ans=0;
string s="123456789";
int main()
{
do{
for(int i=1;i<9;i++) //前一个数占的位数最少1位,最多8位
{
string a,b;
for(int j=0;j<i;j++) a+=s[j]; //前一个数
for(int k=i;k<9;k++) b+=s[k]; //后一个数
ll aa = stoi(a); //string转int (c++11)
ll bb = stoi(b);
ll mul = aa*bb; //乘积
ll temp = mul;
set<int> s;
while(temp) //把各位数放入set
{
if(temp%10==0) break; //出现0就是错误,退出
s.insert(temp%10);
temp/=10;
}
if(s.size()==9) ans=max(ans,mul); //有九个不同的数,就是1-9,更新ans
}
}while(next_permutation(s.begin(),s.end())); //全排列
//cout<<ans;
//cout<<843973902; 错误答案!!! 没看清题目,题目要求答案也只包含1-9各一次
cout<<839542176;
return 0;
}