Formula
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1200 Accepted Submission(s): 415
Problem Description
You are expected to write a program to calculate f(n) when a certain n is given.
Input
Multi test cases (about 100000), every case contains an integer n in a single line.
Please process to the end of file.
[Technical Specification]
Output
For each n,output f(n) in a single line.
Sample Input
2 100
Sample Output
2 148277692
题意:给n,求
思路:直接求的话会TLE,打表会MLE,那么怎么办?分块? 也不行。无法平衡到一个不超过内存和时间的数据。
那么怎么办? 我们想,他会超时是因为什么? 因为算了很多次10000000这种大数字,那么我们能不能只算一次啊~
答案是肯定的。我们把所有的询问都存下来,然后排一个序,每次只在前面的基础上进行递推。最后按照输入顺序输出
这样,我们最多只需要算一遍1~10000000
代码:
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> using namespace std; #define mod 1000000007 #define N 100010 int f[N]; struct Node { int v,id,ans; }query[N]; long long now; bool cmp(Node a,Node b) { if(a.v==b.v) return a.id<b.id; return a.v<b.v; } bool cmp1(Node a,Node b) { return a.id<b.id; } int solve(int l,int r,int t) { int ans=t; for(int i=l+1;i<=r;i++) { now=now*i%mod; ans=now*ans%mod; } return ans; } int main() { int n,cnt=0,t; while(~scanf("%d",&n)) { query[cnt].id=cnt; query[cnt++].v=n; } sort(query,query+cnt,cmp); now=1; query[0].ans=solve(1,query[0].v,1); for(int i=1;i<cnt;i++) query[i].ans=solve(query[i-1].v,query[i].v,query[i-1].ans); sort(query,query+cnt,cmp1); for(int i=0;i<cnt;i++) printf("%d\n",query[i].ans); return 0; }
时间: 2024-12-27 08:37:47