。因此,从已经解决它的人那里领导,我在python中编写了下面的代码。解释这一算法
################################################
### http://www.codechef.com/problems/TAPALIN ###
################################################
def pow(b,e,m):
r=1
while e>0:
if e%2==1:
r=(r*b)%m
e=e>>1
b=(b*b)%m
return r
def cal(n,m):
from math import ceil
c=280000002
a=pow(26, int(ceil(n/2)), m)
if(n%2==0):
return ((52*(a-1+m)%m)*c)%m
else:
return ((52*(((a-1+m)*c)%m))%m+(a*26)%m)%m
c=int(raw_input())
m=1000000007
for z in range(c):
print cal(int(raw_input()),m)
pow的功能是Right-to-left binary method。我不明白的是:
- 280000002从哪里来的?
- 为什么我们需要执行如此多的mod操作?
- 这是一些我不知道的着名算法?
几乎每个在codechef上提交的代码都使用这个算法,但我无法破译它的工作。任何理论的链接将不胜感激。
我仍然无法弄清楚究竟发生了什么。 任何人都可以为这个公式/算法写一个伪代码吗?也帮助我了解此代码的时间复杂性。这让我吃惊的另一件事是,如果我写这个代码:
################################################
### http://www.codechef.com/problems/TAPALIN ###
################################################
def modular_pow(base, exponent):
result=1
while exponent > 0:
if (exponent%2==1):
result=(result * base)%1000000007
exponent=exponent >> 1
base=(base*base)%1000000007
return result
c=int(raw_input())
from math import ceil
for z in range(c):
n=int(raw_input())
ans=modular_pow(26, int(ceil(n/2)))
if(n%2==0):
print ((52*((ans)-1+ 1000000007)%1000000007)*280000002)%1000000007
else:
print ((52*((((ans)-1+ 1000000007)*280000002)%1000000007))%1000000007+(ans*26)%1000000007)%1000000007
这改善了从0.6secs到0.4秒性能。尽管最好的代码在0.0秒内运行。我非常困惑。
感谢您的信息。肯定地(52 *(a-1 + m)%m)=(52 *(a-1)%mi在如此之多的操作之间如此混乱,以至于我从未想到过,尽管这不是一个巨大的提升,这两个代码在0.6秒内执行都是正确的。 – whizzzkid 2013-03-26 07:29:02