VS上能过,但是洛谷全RE

P1009 [NOIP1998 普及组] 阶乘之和

Ze_king @ 2022-08-13 16:27:01

#include<iostream>
#include<cstring>
#include<algorithm>
#define MAXN 5000
using namespace std;
struct bigint {
    int len, a[MAXN];
    bigint(int x=0) {              //构造函数,默认时为零
        memset(a, 0, sizeof(a));
        for (len = 1; x; len++)
            a[len] += x % 10, x /= 10;
        len--;
    }
    int &operator[](int i) {
        return a[i];
    }
    void flatten(int L) {       //处理进位
        len = L;
        for (int i = 1; i < len; i++)
            a[len + 1] += a[len] / 10, a[len] %= 10;
        for (; !a[len];)
            len--;
    }
    void print() {
        for (int i = max(1,len); i >= 1; i--)
            cout << a[i];
    }
};
bigint &operator +(bigint a, bigint b) {    //高精加高精
    bigint c;
    int len = max(a.len, b.len);
    for (int i = 1; i <= len; i++)
        c[i] = a[i] + b[i];
    c.flatten(len+1);
    return c;
}

bigint& operator*(bigint a, int b) {        //高精乘低精
    bigint c;
    int len=a.len;
    for (int i = 1; i <= len; i++)
        c[i] = a[i] *b;
    c.flatten(len + 10);                    //int 最多10位(long long 最多19位)
    return c;
}
int main() {
    bigint ans(0), fac(1);                  //ans是阶乘之和,fac是阶乘
    int n;
    cin >> n;
    for (int i = 1; i <= n; i++){
        fac = fac * i;
        ans = ans+fac;
    }
    ans.print();
    return 0;
}

by sandunder @ 2022-08-13 16:42:28

高精度类的加减重载不能返回引用吧


by Ze_king @ 2022-08-13 16:45:15

@sandunder 我是按照深基上来的,他也是重载


by _cyle_King @ 2022-08-13 16:55:25

@Ze_king 深基怎样我不知道(毕竟我没有),但是您这里的确是错了,返回的引用对象在函数结束时已经被自动删除,所以会出问题。


by Ze_king @ 2022-08-13 18:20:56

@_cyle_King 那为什么VS能过


by _cyle_King @ 2022-08-13 18:23:00

@Ze_king 未定义行为鬼知道会怎样。另附:将您的代码去掉引用后 WA 了,但是有 50 分。


by hyc12528 @ 2022-08-30 22:21:51

int &operator[](int i) { return a[i]; }


|