2017年10月17日 星期二

ITSA第58次月賽 Problem 3. 完整二元樹

http://e-tutor.itsa.org.tw/e-Tutor/mod/programming/view.php?id=38906

import java.util.Scanner;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
Scanner scn =new Scanner(System.in);
int t=Integer.parseInt(scn.nextLine());
while(t--!=0) {
int n=Integer.parseInt(scn.nextLine()),index=1,x=0,b=0;
StringTokenizer tokens = new StringTokenizer(scn.nextLine(),"(),");
int arr[]=new int [tokens.countTokens()/2];
while(tokens.hasMoreTokens()) {
if(index%2==0)
arr[x++]=Integer.parseInt(tokens.nextToken());
else
tokens.nextToken();
index++;
}
for(int i=1;i<=Math.ceil(arr.length/2);i++){
if(Math.abs(arr[i-1]-arr[2*i-1])<=n) {
if(b!=0)
System.out.print(" ");
System.out.printf("%c%c",i+64,i*2+64);
b=1;
}
if(Math.abs(arr[i-1]-arr[2*i])<=n) {
if(b!=0)
System.out.print(" ");
System.out.printf("%c%c",i+64,i*2+65);
b=1;
}
}
System.out.println();
}
}
/*題目:ITSA第58次月賽 Problem 3. 完整二元樹
作者:1010
時間:西元 2017 年10 月 */
}
這題不要看到是樹就想得很害怕又複雜,其實他一點跟樹的演算法都無關仔細看看可以發現規律並用簡單數學就能推出答案囉!


沒有留言:

張貼留言