二叉树应用
http://ac.jobdu.com/problemstatus.php?pid=1543
#include<iostream> #include<stdio.h> #include<stdlib.h> #include<string.h> using namespace std; //#define llu d typedef unsigned long long lld; const int Max = 1000; int path[Max]; void getP_Q(lld n, lld &p, lld &q) { int cnt = 0; lld tmp; while (n != 1) { tmp = n>>1; if (n == tmp * 2) { path[++cnt] = 0; } else { path[++cnt] = 1; } n = tmp; } p = 1; q = 1; while (cnt > 0) { if (path[cnt--] == 0) { q = q + p; } else { p = p + q; } } } lld getN(lld p, lld q) { int cnt = 0; while (p != 1 || q != 1) { if (p > q) { p = p - q; path[++cnt] = 1; } else { q = q - p; path[++cnt] = 0; } } lld n = 1; while (cnt > 0) { if (path[cnt--] == 0) { n = n * 2; } else { n = n * 2 + 1; } } return n; } int main() { int t, kind; lld n, p, q; while(scanf("%d", &t) != EOF) { while (t--) { scanf("%d", &kind); if (kind == 1) { scanf("%llu", &n); getP_Q(n, p, q); printf("%llu %llu\n", p, q); } else { scanf("%llu %llu", &p, &q); printf("%llu\n", getN(p, q)); } } } return 0; }