我觉得我想的算法不错,复杂度比较低,之前好几种都是速度太慢了。
#include <iostream>
#include <vector>
#include <set>
#include <string>
#include <map>
#include <sstream>
using namespace std;
int main()
{
// produce the solution for n form [2, 79]
int n_min = 2; // [2, 79]
int n_max = 79;
int fghij_start = 1234; // [01234, 98765]
int fghij_end = 98765;
int abced_start = 12345;
int abced_end = 98765;
vector<map<int, int>> division_set;
for (int n = n_min; n <= n_max; n++)
{
map<int, int> map_n;
for (int fractions = fghij_start; fractions <= fghij_end; fractions++)
{
int denominator = n*fractions;
if(denominator > abced_start && denominator <= abced_end)
{
set<char> s_10;
stringstream str_num;
for(int num_ele = 0; num_ele < 2; num_ele++)
{
str_num.str("");
if (num_ele == 0)
{
str_num << denominator;
}
else
{
str_num << fractions;
}
string str_digit = str_num.str();
// cout << str_digit << endl;
int len_denominator = str_digit.length();
// cout << "String lenght is" << len_denominator << endl;
for(int m = 0; m < len_denominator; m++)
{
char c_digit = str_digit[m];
s_10.insert(c_digit);
}
}
if(fractions < 10000)
s_10.insert('0');
if(s_10.size() == 10)
{
map_n[denominator] = fractions;
}
s_10.erase(s_10.begin(), s_10.end());
}
}
division_set.push_back(map_n);
// map_n.erase(map_n.begin(), map_n.end());
}
int n;
int flag = 0;
while(cin >> n && n != 0)
{
if (flag)
{
cout << endl;
}
else
{
flag = 1;
}
if (n < n_min || n > n_max)
{
continue;
}
map<int, int> tmp = division_set[n - 2];
if(tmp.empty())
{
cout << "There are no solutions for " << n << "." << endl;
}
else
{
for(map<int, int>::iterator it = tmp.begin(); it != tmp.end(); it++)
{
cout << it->first << " / ";
if(it->second < 10000)
cout << 0 << it->second << " = " << n << endl;
else
cout << it->second << " = " << n << endl;
}
}
}
return 0;
}