Hdu 6211 Pythagoras(暴力+勾股數)

題目地址:http://acm.hdu.edu.cn/showproblem.php?pid=6211

思路:

1.由勾股數性質:對於兩個數n、m(設n<m),(n,m)=1且(m-n)&1=1,則存在勾股數m^2-n^2、2*m*n、m^2+n^2,其中m^2+n^2最大,其餘未知。

2.按照Stern-Brocot tree的生成規則,可以構造出在一定範圍內互質的n和m,判斷是否滿足(m-n)&1=1,若滿足,取m^2-n^2與2*m*n最大值作爲y並記錄其個數,最終求和即可。

3.卡常數,取模運算%mod使用&(mod-1),加快時間。

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>

using namespace std;
typedef long long LL;

const int maxn=1<<17;

int k;
int a[maxn+50];
int ans[maxn+50];

void solve(int l1,int r1,int l2,int r2)
{

    int ml=(l1+l2);
    int mr=(r1+r2);

    if((LL)ml*ml+(LL)mr*mr>(int)1e9) return ;

    if((mr-ml)&1)
    {
        ans[max(mr*mr-ml*ml,2*ml*mr)&(maxn-1)]++;
    }

    solve(l1,r1,ml,mr);
    solve(ml,mr,l2,r2);

}
int main()
{
    int t;
    scanf("%d",&t);
    solve(0,1,1,1);
    while(t--)
    {
        scanf("%d",&k);
        for(int i=0; i<(1<<k); i++) scanf("%d",&a[i]);
        LL sum=0;
        for(int i=0; i<maxn; i++)
        {
            sum+=(LL)ans[i]*a[i&((1<<k)-1)];
        }
        printf("%lld\n",sum);
    }
    return 0;
}



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