求助,确实是tle,但是要怎么优化呢(简单易懂

P1591 阶乘数码

cooronx @ 2021-11-05 23:19:57

#include<iostream>
#include<string>
using namespace std; int ans = 1;
string cal_plus(string l1, string l2) {
    int len1 = l1.length(); int len2 = l2.length();
    if (len1 < len2) {
        for (int i = 1; i <= (len2 - len1); ++i) {
            l1 = "0" + l1;
        }
    }
    else {
        for (int i = 1; i <= (len1 - len2); ++i) {
            l2 = "0" + l2;
        }
    }
    int ans = 0;
    string out;
    for (int i = l1.length() - 1; i >= 0; --i) {
        int temp = (l1[i] - '0') + (l2[i] - '0') + ans;
        ans = temp / 10;
        temp = temp % 10;
        out = char(temp + '0') + out;
    }
    if (ans != 0) {
        out = char(ans + '0') + out;
    }
    return out;
}
string cal_mutipy(string l1, string l2) {
    int len1 = l1.length(); int len2 = l2.length();

    string midl, mid2, out1, out2;
    for (int i = len2 - 1; i >= 0; --i) {
        int ans = 0;
        string tempstr = "";

        for (int j = 1; j <= len2 - 1 - i; ++j) {
            tempstr += "0";
        }
        for (int j = len1 - 1; j >= 0; --j) {
            int temp = ((l2[i] - '0') * (l1[j] - '0')) + ans;
            ans = temp / 10;
            temp = temp % 10;
            tempstr = char(temp + '0') + tempstr;
        }
        if (ans) tempstr = char(ans + '0') + tempstr;
        out1 = cal_plus(out1, tempstr);
    }
    return out1;
}
string sub(string str1, string str2)
{
    string str;
    int tmp = str1.length() - str2.length();
    int cf = 0;
    for (int i = str2.length() - 1; i >= 0; i--)
    {
        if (str1[tmp + i] < str2[i] + cf)
        {
            str = char(str1[tmp + i] - str2[i] - cf + '0' + 10) + str;
            cf = 1;
        }
        else
        {
            str = char(str1[tmp + i] - str2[i] - cf + '0') + str;
            cf = 0;
        }
    }
    for (int i = tmp - 1; i >= 0; i--)
    {
        if (str1[i] - cf >= '0')
        {
            str = char(str1[i] - cf) + str;
            cf = 0;
        }
        else
        {
            str = char(str1[i] - cf + 10) + str;
            cf = 1;
        }
    }
    str.erase(0, str.find_first_not_of('0'));
    return str;
}

//递归处理
string dg(string x) {

    if (x == "1") {
        return "1";
    }
    return cal_mutipy(x,dg(sub(x,"1")));
}
int main() {
    int n; cin >> n;
    for (int i = 1; i <= n; ++i) {
        string a, b; cin >> a >> b;
        string ans = dg(a);//寻找次数
        string::size_type pos;
        pos = ans.find(b);
        int cnt = 0;
        while (pos!= string::npos) {
            pos = ans.find(b, pos+1);
            ++cnt;
        }
        cout << cnt<< endl;
    }
    return 0;
}

为什么我感觉我和题解的思路是一样的,也是o方的复杂度嗄


by nzcnnr @ 2021-12-11 22:15:48

我与你志同道合


|