码迷,mamicode.com
首页 > 其他好文 > 详细

ACdream1187-Rational Number Tree-模拟/找规律

时间:2016-02-18 00:05:29      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:

找到规律模拟就可以了,用DFS模拟很简洁,用循环模拟比较直观(大概吧)

注意输入输出用%llu,1ULL<<64=0!被这几个小问题卡了好久

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

using namespace std;

int T;
unsigned long long n,p,q;
unsigned long long path;
int lev;

int main()
{
    scanf("%d",&T);
    for(int kase=1;kase<=T;kase++)
    {
        int op = 0;
        scanf("%d",&op);
        if(op == 1)
        {
            scanf("%llu",&n);
            lev=0;path=0;

            while((1ULL<<lev) <= n)
            {
                lev++;
                if(lev==64)break;
            }
            lev--;

            path = n - (1ULL<<lev);
            p=1;q=1;
            //printf("lev=%lld path=%lld\n",lev,path);

            for(int i=lev-1;i>=0;i--)
            {
                if(path & (1ULL<<i)) p=p+q;
                else q = p+q;
            }
            printf("Case #%d: %llu %llu\n",kase,p,q);
        }
        else if(op == 2)
        {
            scanf("%llu%llu",&p,&q);

            unsigned long long tp = p,tq = q;
            lev=0;path=0;
            while(true)
            {
                //printf("%llu %llu\n",p,q);
                if(p==1ULL && q==1ULL) break;

                if(p > q) p -= q;
                else q -= p;
                lev++;
            }

            for(int i=0;i<lev;i++)
            {
                if(tp > tq)
                {
                    path += (1ULL<<i);
                    tp -= tq;
                }
                else
                    tq -= tp;
            }
            //printf("lev=%lld path=%lld\n",lev,path);
            printf("Case #%d: %llu\n",kase,path+(1ULL<<lev));
        }
    }
}

 

ACdream1187-Rational Number Tree-模拟/找规律

标签:

原文地址:http://www.cnblogs.com/helica/p/5196855.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!