[ACM] HDU 5139 Formula (离线处理)

来源:互联网 发布:sql安装挂起清除工具 编辑:程序博客网 时间:2024/04/28 21:39

Formula




Problem Description
f(n)=(i=1nini+1)%1000000007
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]
1n10000000
 

Output
For each n,output f(n) in a single line.
 

Sample Input
2100
 

Sample Output
2148277692
 

Source
BestCoder 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;}



0 1
原创粉丝点击