-
题目描述:
-
有一棵无限完全二叉树,他的根节点是1/1,且任意一个节点p/q的左儿子节点和右儿子节点分别是,p/(p+q)和(p+q)/q。如下图:
它的层次遍历结果如下:
1/1, 1/2, 2/1, 1/3, 3/2, 2/3, 3/1,...
有如下两类问题:
1.找到层次遍历的第n个数字。如,n为2时,该数字为1/2;
2.给定一个数字p/q,输出它在层次遍历中的顺序,如p/q为1/2时,其顺序为2;
-
输入:
-
输入包含多组测试用例,输入的第一行为一个整数T,代表共有的测试用例数。
接下去T行每行代表一个测试用例,每个测试用例有如下两种类型
1.1 n。输出层次遍历中,第n个数字。
2.2 p q。输出p/q在层次遍历中的顺序。
1 ≤ n, p, q ≤ 2^64-1
-
输出:
-
对于每个测试用例,若其类型为1,输出两个整数p q,代表层次遍历中第n个数字为p/q。
若其类型为2,输出一个整数n,代表整数p/q在层次遍历的中的顺序n。
数据保证输出在[1,2^64-1]范围内。
思路:
看到题目第一想到的就是直接遍历,那么对于第N个结点的p/q输出时间复杂度为O(N)。显然存在可以优化的地方。由于题目中的树为完全二叉树,由完全二叉树的性质可知:对于结点n,n的父节点为n/2且n为偶数时为父节点的左节点,奇数为右结点,由此若知道n则可以得到一条由结点n到根节点的路径及当前结点是父节点的左孩子或是右孩子(代码中我采用Stack<Integer>来存储0代表右1代表左,)。根节点p/q已知则根据路径可推出结点n的p/q值时间复杂度O(logN)。对于由p/q求n,根据题意可以知道当p>q的时候这一节点为父节点的左孩子,p<q的时候为右孩子。这样就也能得到一条路径了n自然也就可以推出来了,时间复杂度一样为O(logN)。
由于题目要求输出在[1,2^64-1]范围内。所以我采用了BigInteger来存储数值。开始用int的时候总accept不了,想了好久才发现这个要求。。。。import java.math.BigInteger; import java.util.*; public class Main { public static void main(String[] args) { BigInteger p=new BigInteger("1"); BigInteger q=new BigInteger("1"); BigInteger n = new BigInteger("1") ; Scanner cin = new Scanner(System.in); int testNum; while(cin.hasNext()){ testNum=cin.nextInt(); for(int i=0;i<testNum;i++){ switch(cin.nextInt()){ case 1: n=cin.nextBigInteger(); findpq(n); break; case 2: p=cin.nextBigInteger(); q=cin.nextBigInteger(); findn(p,q); break; default : i=i-1; break; } } } } private static void findpq(BigInteger n){ Stack<Integer> s=new Stack<Integer>(); BigInteger p=new BigInteger("1"); BigInteger q=new BigInteger("1"); while(!n.equals(BigInteger.valueOf(1))){//遍历寻找路径 s.push(n.mod(BigInteger.valueOf(2)).intValue()); n=n.divide(BigInteger.valueOf(2)); } while(!s.empty()){//推导p/q if(s.pop().equals(new Integer(0))) q=p.add(q); else p=p.add(q); } System.out.println(p+" "+q); } private static void findn(BigInteger p,BigInteger q){ BigInteger n=BigInteger.valueOf(1); Stack<Integer> s=new Stack<Integer>(); while((!p.equals(new BigInteger("1")))||(!q.equals(new BigInteger("1")))){//遍历寻找路径 if(p.compareTo(q)<0){ s.push(0); q=q.subtract(p); } else { s.push(1); p=p.subtract(q); } } while(!s.empty()){//推导n if(s.pop().equals(new Integer(0))) n=n.multiply(BigInteger.valueOf(2)); else n=n.multiply(BigInteger.valueOf(2)).add(BigInteger.valueOf(1)); } System.out.println(n); } }