iTheresaApocalypse @ 2023-02-14 10:52:36
#include<bits/stdc++.h>
using namespace std;
#define maxn 2000
int n;
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[i+1]+=a[i]/10,a[i]%=10;
for(;!a[len];)
len--;
}
void print()
{
for(int i=max(len,1);i>=1;i--)
printf("%d",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;
}
int main()
{
cin>>n;
Bigint f[5050];
f[1] = Bigint(1);
f[2] = Bigint(2);
for(int i=3;i<=n;i++)
{
f[i]=f[i-1]+f[i-2];
}
f[n].print();
return 0;
}
by ud2_ @ 2023-02-14 11:03:48
STATUS_ACCESS_VIOLATION
.
在这里是因为栈空间不够;Windows 下默认分配的 2 MB 栈放不下 40 MB 的数组 f
。
by iTheresaApocalypse @ 2023-02-14 14:12:11
@ud2_ 感谢!
by Roger_Spencer @ 2023-03-20 09:25:30
#include <bits/stdc++.h>
using namespace std;
#define LL long long
#define endl "\n"
const int N = 1e5 + 10;
const int M = 5510;
int dp[N];
vector<int> add(vector<int> &A, vector<int> &B)
{
if (A.size() < B.size()) return add(B, A);
vector<int> C;
int t = 0;
for (int i = 0; i < A.size(); i ++ )
{
t += A[i];
if (i < B.size()) t += B[i];
C.push_back(t % 10);
t /= 10;
}
if (t) C.push_back(t);
return C;
}
void solve()
{
int n;
cin >> n;
if ( n == 1)
{
cout << 1 << endl;
return;
}
vector<int> A, B, C, D;
A.push_back(1);
B.push_back(1);
for (int i = 2; i <= n; i ++ )
{
C = add(A, B);
A = B;
B = C;
}
for (int i = C.size() - 1; i >= 0; i -- ) cout << C[i];
cout << endl;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
solve();
return 0;
}