UVA 10479 The Hendrie Sequence (规律+递归)

题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1420

#include<bits/stdc++.h>
using namespace std;

#define debug puts("YES");
#define rep(x,y,z) for(int (x)=(y);(x)<(z);(x)++)
#define ll unsigned long long

#define lrt int l,int r,int rt
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define root l,r,rt
#define mst(a,b) memset((a),(b),sizeof(a))
const int  maxn =1e5+5;
const int mod=9999991;
const int ub=1e6;

ll powmod(ll x,ll y){ll t; for(t=1;y;y>>=1,x=x*x%mod) if(y&1) t=t*x%mod; return t;}
ll gcd(ll x,ll y){return y?gcd(y,x%y):x;}
/*
题目大意:给定一个序列的生成方式,
要求输出第n项是什么。

找规律+递归求解。
首先可以把整体序列按1,1,2,4,8,16,,分割,
然后看规律,,具体证明可能有些复杂,
但可以发现,当前位置s的序列,是一个s-2序列,2个s-3序列,三个s-4序列。。。构成,
这样我们可以递归求解(x,y),
第x个序列,第y个数。

y可以按上述规律降解,详见代码,递归层数并不多。

注意一个wa点,用unsigned long  long,不能用I64d读入和输出。


*/
ll n,pw2[64];

ll dfs(ll x,ll y){
    if(x==1LL) return 1LL;
    if(x==2LL)  return y==1LL?0LL:2LL;
    ll tim=1,c=x-2LL;
    while(c>=1&&1LL*tim*pw2[c-1]<y) y-=1LL*tim*pw2[c-1],c--,tim++;
    if(c<1){
        return y==x?1LL*x:0LL;
    }
    else{
        y=y%pw2[c-1];
        if(y==0) y=pw2[c-1];
        return dfs(c,y);
    }
}

int main(){
    pw2[0]=1LL;for(int i=1;i<64;i++) pw2[i]=2LL*pw2[i-1];
    while(scanf("%Ilu",&n)&&n){///不能用I64d方法输入
        if(n==1) puts("0");
        else{
            ll cnt=1LL,t=1LL;
            while(2LL*t<n) cnt++,t<<=1;
            n-=t;
            printf("%Ilu\n",dfs(cnt,n));
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37451344/article/details/84109940