最后一个过不了(前三个评测能跑,本地不能跑)

P1009 [NOIP1998 普及组] 阶乘之和

_TeaClaudz_ @ 2023-07-14 13:51:57

#include<bits/stdc++.h>
using namespace std;

void multi(vector<int> &v, int j) {
    int i;
    for(i = 0; i < v.size(); ++i) {
        v[i] *= j;
    }
    for(i = 0; i < v.size()-1; ++i) {
        if(v[i] >= 10) v[i+1] += v[i] / 10, v[i] %= 10;
    }
    while(v[i] >= 10) {
        v.push_back(v[i] / 10);
        v[i] %= 10;
    }
    while(v.back() == 0) v.pop_back();
    return;
}

void add(vector<int> &s, vector<int> t) {
    vector<int> c;
    c.clear();
    int i;
    for(i = 0; i < s.size() || i < t.size(); ++i) {
        if(i < s.size()) {
            if(i == c.size() - 1) c[i] += s[i];
            else c.push_back(s[i]);
        }
        if(i < t.size()) {
            if(i == c.size()) c.push_back(t[i]);
            else c[i] += t[i];
        }
        if(c[i] >= 10) {
            c.push_back(c[i] / 10);
            c[i] %= 10;
        }
    }
    if(c[i] >= 10) {
        c.push_back(c[i] / 10);
        c[i] %= 10;
    }
    while(c.back() == 0) c.pop_back();
    s.swap(c);
    return;
}

int main() {
    vector<int> s;
    int n;
    s.clear();
    s.push_back(0);
    cin >> n;
    for(int i = 1; i <= n; ++i) {
        vector<int> t;
        t.clear();
        t.push_back(1);
        for(int j = i; j >= 1; --j) {
            multi(t, j);
            /*
            cout << "t:";
            for(int i = t.size() - 1; i >= 0; --i) {
                cout << t[i];
            }
            cout << " j:" << j << endl;
            */
        }
        add(s, t);
        /*
        cout << "s:";
        for(int i = s.size() - 1; i >= 0; --i) {
            cout << s[i];
        }
        cout << endl;
        */
    }
    for(int i = s.size() - 1; i >= 0; --i) {
        cout << s[i];
    }
    return 0;
}

第一个评测没问题,但本地有时候是833(正确),有时候千位是1,百位1到9随机变化


by WangSH2012 @ 2023-07-19 21:05:31

题解


|