POJ 1001 解题分析

Technorati 标签: ACM,POJ

这道题做了很多很多天,实在是非常不爽。一向最恶心高精度计算的题了,等有空了就写套类库出来,以后碰见就用=w=

题目描述

题目链接:POJ 1001

Exponentiation

Time Limit: 500MS
Memory Limit: 10000K

Total Submissions: 71143
Accepted: 16704

Description

Problems involving the computation of exact values of very large magnitude and precision are common. For example, the computation of the national debt is a taxing experience for many computer systems.
This problem requires that you write a program to compute the exact value of Rn where R is a real number ( 0.0 < R < 99.999 ) and n is an integer such that 0 < n<= 25.

Input

The input will consist of a set of pairs of values for R and n. The R value will occupy columns 1 through 6, and the n value will be in columns 8 and 9.

Output

The output will consist of one line for each line of input giving the exact value of R^n. Leading zeros should be suppressed in the output. Insignificant trailing zeros must not be printed. Don't print the decimal point if the result is an integer.

Sample Input

95.123 12
0.4321 20
5.1234 15
6.7592  9
98.999 10
1.0100 12

Sample Output

548815620517731830194541.899025343415715973535967221869852721
.00000005148554641076956121994511276767154838481760200726351203835429763013462401
43992025569.928573701266488041146654993318703707511666295476720493953024
29448126.764121021618164430206909037173276672
90429072743629540498.107596019456651774561044010001
1.126825030131969720661201

Hint

If you don't know how to determine wheather encounted the end of input:
s is a string and n is an integer

C++

while(cin>>s>>n)
{
...
}

C

while(scanf("%s%d",s,&n)==2) //to  see if the scanf read in as many items as you want
/*while(scanf(%s%d",s,&n)!=EOF) //this also work    */
{
...
}

Source

East Central North America 1988

解题分析

如果不算高精度的话,实际上是一道非常简单的题o(╯□╰)o,看到好多Java的同学用BigDecimal类直接就AC了,⊙﹏⊙b汗。

难度可以说几乎没有,做这道题才发现其实POJ限制相当松啊,内存居然给10M,时间500MS。

个人觉得本着对自己认真负责的原则,该优化的地方还是要优化一下的,而这道题最值得优化的就是乘方部分:

R^{n}=\lbrace{}R\times{}R^{n-1},\when{}n是奇数\or{}R^{n/2}\times{}R^{n/2},\when{}n是偶数这样能够大幅度减少乘法的次数。

由于输入的数既有小数又有整数,为了方便处理,我们可以将所有的输入都转换为整数,并记录小数点的位置;待计算完毕后,再添加上小数点。

下面给出伪代码:

Procedure R, n Begin
	Shift R to get an integer IntR and e which present where the dot is.
	IntResult <- BigIntegerPow(IntR, n)
	e <- e * n;
	Shift IntResult by e bit to get an BigDecimal result.
	Trim the result to remove zero at front of integer and zero at end of decimal.
End Procedure

优化余地

做乘法的时候,可以把乘数分为若干段,分别相乘后再相加。

还可以在一开始转换的时候,就不用字符串存储,而用若干个long分别存储若干段。

总结

我只能说,这道题的数据和格式要求非常变态,真的非常非常变态╮(╯▽╰)╭。下面给不明真相的同学一套测试数据:

POJ1001TestCase.zip

posted @ 2010-07-10 21:55  HCOONa  阅读(1604)  评论(1编辑  收藏  举报