山東省第四屆ACM大學生程式設計競賽-Alice and Bob(二進位制&&找規律)

kewlgrl發表於2016-04-13

Alice and Bob

Time Limit: 1000MS Memory limit: 65536K

題目描述

    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

示例輸出

2
0

提示

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,展開這個式子後,求x^q的係數。


解題思路:

(a0*x^(2^0)+1) * (a1 * x^(2^1)+1)*.......*(an-1 * x^(2^(n-1))+1)

展開看看:

當n=0:

1+a0*x^20

當n=1:

1+ a0 *a1*x^20*x^21+a1*x^21+a0*x^20

當n=2:

1+ a0 *a1*a2*x^20*x^21*x^22+a2*x^22+a1*x^21+a0*x^20+a2*a1*x^22*x^21+a1*a0*x^21 *x^20+ a2*a0*x^22*x^20

………………


所以展開式中不存在可以合併同類項的情況,直接藉助係數a就可以運算。


先看下面這張表(q在題目中是x的指數)


q   二進位制      x的指數

1  1         (20)

2  10       (21)

3  11       (21 +20)

4  100     (22)

5  101     (22 +20)

6  110     (22 +21)

7  111     (22 +21+20)

8  1000   (23)

9  1001   (23+20)


發現了什麼規律?

對了,就是把指數轉換成二進位制數,再把二進位制數中所有“1”的權值都加起來!!


舉個栗子:

q=3時,x^3的係數=a[1]*a[0];

q=6時,x^6的係數=a[2]*a[1];

q=7時,x^7的係數=a[2]*a[1]*a[0]

q=10時,x^10的係數=a[3]*a[1]


這些得到的係數就是題目要求的答案呀~


還有個坑,就是用C語言的printf輸出死活都是WA,一改成C++cin就AC了,估計是long long的格式控制問題吧。。

(⊙v⊙)嗯發現了,我在山理工的oj下提交這道題long long 不能用%I64d,用%lld就能過了~


下面上程式碼:

/*
* Copyright (c) 2016, 煙臺大學計算機與控制工程學院
* All rights reserved.
* 檔名稱:number.cpp
* 作    者:單昕昕
* 完成日期:2016年4月12日
* 版 本 號:v1.0
*/
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <time.h>
#include <stdlib.h>
using namespace std;
int a[51];//a0~an-1
long long ans,p;
int main()
{
    int t,i,n,q;
    cin>>t;
    while(t--)
    {
        cin>>n;
        for(i=0; i<n; ++i)
            cin>>a[i];
        cin>>q;
        while(q--)
        {
            i=0;
            ans=1;
            cin>>p;
            while(p)
            {
                //注意!!當此n下無指數p時,即位數超出n
                if(i>=n)
                {
                    ans=0;
                    break;
                }//下面是一個類似於轉換二進位制的過程
                if(p%2)
                    ans=(ans*a[i])%2012;
                ++i;
                p/=2;
            }
            cout<<ans<<endl;
        }
    }
    return 0;
}


相關文章