hdu 4919 數論+大數

//f[n]=4f[k]+6k (n==2k+1)
//    =2f[k]+2[k-1]+4k-4  (n==2k)

要麼、擴棧語句

G++:
int size = 128 << 20; // 128MB  如果題目64M,自然 64<<20
    char *p = (char*)malloc(size) + size;
    __asm__("movl %0, %%esp\n" :: "r"(p));

C++:
#pragma comment(linker, "/STACK:102400000,102400000")

要麼、將遞歸轉爲非遞歸求解(標稱這麼做的)

//f[n]=4f[k]+6k (n==2k+1)
//    =2f[k]+2[k-1]+4k-4  (n==2k)
BigInteger contribution(const BigInteger &n, const BigInteger &coefficient) {
    BigInteger result;
    if (n[0] % 2) {
        result = (n / 2) * 6;
    } else {
        result = n * 2 - 4;
    }
    return result * coefficient;
}
//co[0] *f[x]+ co[1] *f[x+1]
//iff(x=2k)     =co[0]*f[2k]+co[1] *f[2k+1]=co[0]*(2f[k]+2f[k-1]+4*k-4)+co[1]*(4f[k]+6*k)
//              =2co[0]f[k-1]+(2co[0]+4co[1])f[k]+ co[0](4*k-4)+co[1]*6k;
//              x爲偶數時,x傳入時 爲2*2k-4,  (x+1)傳入時爲(2k+1)/2*6

//iff(x=2k+1)   =co[0]*f[2k+1]+co[1] *f[2k+2]=co[0]*(4f[k]+6*k)+co[1]*(2f[k]+2f[k+1]+4*(k+1)-4)
//              =(4co[0]+2co[1])f[k]+2co[1]f[k+1]+ co[0](6*k)+co[1]*(4*(k+1)-4);
//              x爲奇數時,x傳入時 爲(2k+1)/2*6,  (x+1)傳入時爲(2k+1+1)*2-4
int main()
{
    while (scanf("%s", buffer) == 1) {
        BigInteger n(buffer);
        BigInteger result = 0;
        std::vector <BigInteger> coefficient;
        coefficient.push_back(1);
        coefficient.push_back(0);
        while (n.length) {
            result = result + contribution(n, coefficient[0]) + contribution(n + 1, coefficient[1]);
            std::vector <BigInteger> new_coefficient;
            if (n[0] % 2) {
                n = n / 2;
                new_coefficient.push_back((coefficient[0] * 4) + (coefficient[1] * 2));
                new_coefficient.push_back((coefficient[1] * 2));
            } else {
                n = (n / 2) - 1;
                new_coefficient.push_back((coefficient[0] * 2));
                new_coefficient.push_back((coefficient[0] * 2) + (coefficient[1] * 4));
            }
            coefficient = new_coefficient;
        }
        result.print();
    }
    return 0;
}


發佈了81 篇原創文章 · 獲贊 5 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章