HDU 5139数据离线处理

时间:2022-08-19 00:31:20

此题可以找到规律f(n) = 1! * 2! *...*n!, 如果直接打表的话,由于n比较大(10000000),所以会超内存,这时候就要用到离线处理数据,就是先把数据存起来,到最后在暴力一遍求解就行了,代码如下

代码一(超内存):

 #include <stdio.h>

 const long long mod = ;
const int N = ;
long long a[N]; int main()
{
a[] = a[] = ;
for (int i = ; i < N; i++)
{
a[i] = a[i - ] * i % mod;
} for (int i = ; i < N; i++)
{
a[i] = a[i - ] * a[i] % mod;
}
int n;
while (~scanf("%d", &n))
{
printf("%I64d\n", a[n]);
}
return ;
}

代码二(AC)

 #include <stdio.h>
#include <vector>
#include <map>
const long long mod = ;
using namespace std; int main()
{
int n;
vector<int> a;
map<int, long long> vis;
while (scanf("%d", &n) != EOF)
{
a.push_back(n);
vis[n] = -;
}
long long prep = , nowp, prea = , nowa;
for (int i = ; i <= ; i++)//离线算法
{
nowp = prep * i % mod;//相当于求阶乘
prep = nowp;
nowa = nowp * prea % mod;//求n个阶乘的乘积
prea = nowa;
if (vis.count(i))
{
vis[i] = nowa;
}
}
for (int i = ; i < a.size(); i++)//暴力一遍
{ printf("%I64d\n", vis[a[i]]);
}
return ;
}

离线算法确实挺神奇的,要深刻理解才能做题