티스토리 뷰

이진트리로 주어진 사칙연산이 유효한지 출력하는 문제다

입력이 조금 복잡하게 들어오는거 빼고는 크게 어렵지는 않은 문제다!

 

문제의 조건을 생각해보면 내가 현재 노드가 숫자일 때, 연산자일 때 나눠보면 된다

 

1. 숫자일 때 => 자식을 가지고 있으면 무조건 false다

2. 연산자라면 => 내 자식 두명을 재귀타고가서 둘다 참이라면 true다

 

코드가 좀 헷갈릴 수 있지만 재귀적으로 생각하면 쉽게 풀 수 있다!

 

소스코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import java.util.*;
import java.io.*;
 
 
public class Solution {
    public static char[] tree = new char[222];
    public static int n;
    public static void init() {
        for(int i=0;i<n;i++) tree[i]=0;
    }
    public static boolean inner(int x) {
        return (1<=&& x<=&& tree[x]==0);
    }
    public static boolean solve(int x) {
        if(x>n) return false;
        char c = tree[x];
        if('0' <= c && c<='9') {
            if((inner(x*2&& inner(x*2+1)) || (x*2>n) && (x*2+1>n)) return true;
            return false;
        }else return (solve(x*2)&solve(x*2+1));
    }
    public static void main(String[] args) throws FileNotFoundException {
        System.setIn(new FileInputStream("res/input.txt"));
        Scanner sc = new Scanner(System.in);
        
        for(int tc=1;tc<=10;tc++) {
            n = sc.nextInt();
            init();
            String s = sc.nextLine();
            for(int i=1;i<=n;i++) {
                s=sc.nextLine();
                String[] sa = s.split(" ");
                tree[i] = sa[1].charAt(0);
            }
            int ans = (solve(1)==true) ? 1:0;
            System.out.println("#"+tc+" "+ans);
        }
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

'알고리즘 > Java' 카테고리의 다른 글

[SWEA] 9659 다항식 계산  (0) 2020.04.03
[SWEA] 1244 최대상금  (0) 2020.02.17
[JUNGOL] 1828 냉장고  (0) 2020.02.12
[SWEA] 8931 제로  (0) 2020.01.21
[SWEA] 9229 한빈이와 SpotMart  (0) 2020.01.21
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함