2017.11.7 T1 2044
样例数据
输入
3 997
2 3 5
输出
61
分析:暴力的话最多只能O(
N2
),考虑能否递推,手玩样例发现:
61=2+3+2∗3+5+3∗5+2∗3∗5
好像很废话,但是看到后面的数用到了前面的数(好像也很废话(⊙o⊙)…),我就记一个fro,先ans=2,fro=2,然后ans+=3+3*fro,fro变成3+3*fro,最后5*fro,得到答案。于是就变成O( N <script type="math/tex" id="MathJax-Element-219">N</script>)的啦。
代码
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<string>
#include<ctime>
#include<cmath>
#include<algorithm>
#include<cctype>
#include<iomanip>
#include<queue>
#include<set>
using namespace std;
int getint()
{
int sum=0,f=1;
char ch;
for(ch=getchar();!isdigit(ch)&&ch!='-';ch=getchar());
if(ch=='-')
{
f=-1;
ch=getchar();
}
for(;isdigit(ch);ch=getchar())
sum=(sum<<3)+(sum<<1)+ch-48;
return sum*f;
}
long long getlong()
{
long long sum=0,f=1;
char ch;
for(ch=getchar();!isdigit(ch)&&ch!='-';ch=getchar());
if(ch=='-')
{
f=-1;
ch=getchar();
}
for(;isdigit(ch);ch=getchar())
sum=(sum<<3)+(sum<<1)+ch-48;
return sum*f;
}
const int maxn=100010;
int n;
long long p,a[maxn],fro,hr,ans;
long long ksc(long long x,long long y)
{
long long res=0;x=x%p;
for(;y>=1;y=y>>1,x=(x+x)%p)
if(y&1)
res=(res+x)%p;
return res;
}
int main()
{
freopen("sum.in","r",stdin);
freopen("sum.out","w",stdout);
n=getint(),p=getlong();
for(int i=1;i<=n;++i)
a[i]=getlong();
ans=a[1],fro=a[1];
for(int i=2;i<=n;++i)
{
ans=(ans+a[i])%p;
hr=ksc(a[i],fro);//模数太大,用快速乘
ans=(ans+hr)%p;
fro=hr;//参见我上面的递推
fro=(fro+a[i])%p;
}
cout<<ans<<'\n';
return 0;
}
本题结。