[ACM] HDU 5139 Formula (離線處理),hdu5139
Formula
Problem Descriptionf(n)=(∏i=1nin−i+1)%1000000007
You are expected to write a program to calculate f(n) when a certain n is given.
InputMulti test cases (about 100000), every case contains an integer n in a single line.
Please process to the end of file.
[Technical Specification]
1≤n≤10000000
OutputFor each n,output f(n) in a single line.
Sample Input
2100
Sample Output
2148277692
SourceBestCoder Round #21
解題思路:
通過公式可以得出這樣的結論: f(n)=1! *2! *3!*....*n! ,n的範圍10000000,如果直接打表的話,會超記憶體,本題就是卡記憶體。所以不能開那麼大的數組。方法是對輸入的資料進行離線處理,即統一輸入,統一處理,最後統一輸出,輸入的時候用pair<int,int>類型的vector記錄下記錄下每次輸入的n以及輸入的次序,對pair進行sort排序,是根據first從小到大排序的,所以讓first等於輸入的n,對其排序,然後n從小到大根據公式線性求值就可以了,注意輸入的n可能有相同的。
代碼:
#include <iostream>#include <stdio.h>#include <vector>#include <algorithm>#include <string.h>using namespace std;const int maxn=100002;const int mod=1000000007;int ans[maxn];vector<pair<int,int> >vc;int n;int cnt=0;int main(){ while(scanf("%d",&n)!=EOF) { vc.push_back(make_pair(n,cnt++)); } sort(vc.begin(),vc.end()); int MAX=vc[cnt-1].first; long long tp=1,result=1; int t=0; for(int i=1;i<=MAX;i++) { tp=tp*i; if(tp>=mod) tp%=mod; result=result*tp; if(result>=mod) result%=mod; while(t<cnt&&vc[t].first==i)//輸入的時候n可能有重複的 { ans[vc[t].second]=result; t++; } } for(int i=0;i<cnt;i++) cout<<ans[i]<<endl; return 0;}