大致看了一下题解,和我想的一样就是一道高精乘低精的模板题啊?阶乘也用递推优化过了,怎么会超时呢?
代码中的add和mul完全是照模板写的,求助
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string add(string, string);
string mul(string, int);
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t;
int n, maxn = 1;
char a;
string fac[1001] = {"0", "1"};
cin >> t;
for (int i = 1; i <= t; i++)
{
cin >> n >> a;
if (n <= maxn)
cout << count(fac[n].begin(), fac[n].end(), a) << "\n";
else
{
for (int j = maxn + 1; j <= n; j++)
fac[j] = mul(fac[j - 1], j);
maxn = n;
cout << count(fac[n].begin(), fac[n].end(), a) << "\n";
}
}
return 0;
}
string add(string str1, string str2)
{
string str = "";
int str1_len = str1.length(), str2_len = str2.length(), temp = 0;
bool carry = 0;
if (str1_len < str2_len)
for (int i = 1; i <= str2_len - str1_len; i++)
str1 = '0' + str1;
else
for (int i = 1; i <= str1_len - str2_len; i++)
str2 = '0' + str2;
str1_len = str1.length(), str2_len = str.length();
for (int i = str1_len - 1; i >= 0; i--)
{
temp = str1[i] - '0' + str2[i] - '0' + carry;
carry = temp / 10;
temp %= 10;
str = char(temp + '0') + str;
}
if (carry == 1)
str = '1' + str;
return str;
}
string mul(string a, int b)
{
string str = "", temp_num = "";
int temp_digit = 0;
int a_len = a.length(), carry = 0;
for (int i = a_len - 1; i >= 0; i--)
{
temp_num = "";
temp_num.insert(0, a_len - 1 - i, '0');
temp_digit = (a[i] - '0') * b + carry;
carry = temp_digit / 10;
temp_digit %= 10;
temp_num = char(temp_digit + '0') + temp_num;
str = add(str, temp_num);
}
if (carry != 0)
str = to_string(carry) + str;
str.erase(0, str.find_first_not_of('0'));
if (str.empty())
str = "0";
return str;
}