90 pts TLE on #4

P1591 阶乘数码

YC_Lyy @ 2024-12-04 21:28:31

#include <bits/stdc++.h>
#define Written return
#define by 0
#define YC_Lyy ;
using namespace std;

int t, n, ans;
char a;
string ss1, ss2;

string f(string s1, string s2)
{
    string str;
    int len1 = s1.length();
    int len2 = s2.length();
    if (len1 < len2)
    {
        for (int i = 1; i <= len2 - len1; i++)
        {
            s1 = '0' + s1;
        }
    }
    else
    {
        for (int i = 1; i <= len1 - len2; i++)
        {
            s2 = '0' + s2;
        }
    }
    len1 = s1.length();
    int cf = 0;
    int temp;
    for (int i = len1 - 1; i >= 0; i--)
    {
        temp = s1[i] - '0' + s2[i] - '0' + cf;
        cf = temp / 10;
        temp %= 10;
        str = char(temp + '0') + str;
    }
    if (cf != 0) str = char(cf + '0') + str;
    return str;
}

string fs(string str1, string str2)
{
    if (str1 == "0" || str2 == "0")
        return "0";
    string str;
    int len1 = str1.length();
    int len2 = str2.length();
    string tempstr;
    for (int i = len2 - 1; i >= 0; i--)
    {
        tempstr = "";
        int temp = str2[i] - '0';
        int t = 0;
        int cf =  0;
        if (temp != 0)
        {
            for (int j = 1; j <= len2 - 1 - i; j++)
                tempstr += "0";
            for (int j = len1 - 1; j >= 0; j--)
            {
                t = (temp * (str1[j] - '0') + cf) % 10;
                cf = (temp * (str1[j] - '0') + cf) / 10;
                tempstr = char(t + '0') + tempstr;
            }
            if (cf != 0) tempstr = char(cf + '0') + tempstr;
        }
        str = f(str, tempstr);
    }
    str.erase(0, str.find_first_not_of('0'));
    return str;
}

int main()
{
    cin >> t;
    for (int i = 1; i <= t; i++)
    {
        cin >> n >> a;
        ans = 0;
        ss1 = "1";
        for (int j = 2; j <= n; j++)
        {
            int k = j;
            ss2 = "";
            while (k)
            {
                ss2 = char(k % 10 + '0') + ss2;
                k /= 10;
            }
            ss1 = fs(ss1, ss2);
        }
        for (int j = 0; j <= ss1.size(); j++)
            if (ss1[j] == a)
                ans++;
        cout << ans << endl;
    }
    Written by YC_Lyy
}

|