ACdream1187-Rational Number Tree-模拟/找规律
找到规律模拟就可以了,用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)); } } }