Alice and Bob like playing games very much.Today, they introduce a new game.
There is a polynomial like this: (a0*x^(2^0)+1) * (a1 * x^(2^1)+1)*.......*(an-1 * x^(2^(n-1))+1). Then Alice ask Bob Q questions. In the expansion of the Polynomial, Given an integer P, please tell the coefficient of the x^P.
Can you help Bob answer these questions?
输入
The first line of the input is a number T, which means the number of the test cases.
For each case, the first line contains a number n, then n numbers a0, a1, .... an-1 followed in the next line. In the third line is a number Q, and then following Q numbers P.
1 <= T <= 20
1 <= n <= 50
0 <= ai <= 100
Q <= 1000
0 <= P <= 1234567898765432
输出
For each question of each test case, please output the answer module 2012.
示例输入
1
2
2 1
2
3
4
示例输出
20
提示
The expansion of the (2*x^(2^0) + 1) * (1*x^(2^1) + 1) is 1 + 2*x^1 + 1*x^2 + 2*x^3来源
2013年山东省第四届ACM大学生程序设计竞赛
题意:已知公式: (a0*x^(2^0)+1) * (a1 * x^(2^1)+1)*.......*(an-1 * x^(2^(n-1))+1).,a[0]到a[n]由自己输入,之后输入P,求x^p的系数,,
思路:首先把前四项因式展开,得到以下结果:
指数式 对应系数
x^1 a0
x^2 a1
x^3 a0*a1
x^4 a2
x^5 a0*a2
x^6 a1*a2
x^7 a0*a1*a2
发现规律之后,首先想到的是递推,但由于P值太大,开不了数组,递推的时候发现一个很准的规律,就是x^p的系数由p的二进制数中0、1的排列决定,
比如:p=7时,7的二进制位111,三位都是1,则7的系数为a0*a1*a2,5的二进制位101,只有第二位为0,故系数为a0*a2而没有乘上a1, 再看p=6时,6的二进制为110,第三位是0,故系数为a1*a2而没有乘上a0;
不难发现,将p转化为二进制后,从最后一位开始,依次对应a0,a1,a2,....an;看每一位是0还是1,如果是1则乘上对应的ai值,,,
还有一点要注意,当p为0时x^0系数为1;
由于P太大,之前用%I64d输出,提交总是WA,最后用C++水过。。
最后要求结果对2012取模,需要在程序中执行。。
以下AC代码:
#include <stdio.h>
#include<iostream>
using namespace std;
int a[55];
int main()
{
long long p;
int t,n;
int k,i;
int q;
long long sum;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
scanf("%d",&q);
while(q--)
{
sum=1;
k=0;
cin>>p;
while (p!=0)
{
if(k>=n)
{
sum=0;
break;
}
if(p%2)
{
sum*=a[k];
}
++k;
p/=2;
sum=sum%2012;
}
cout<<sum<<endl;
}
}
return 0;
}