[SWEA] 1233 사칙연산 유효성 검사

cheeeese·2022년 8월 9일
0

코딩테스트 연습

목록 보기
128/151
post-thumbnail

📖 문제

https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV141176AIwCFAYD

💻 내 코드

파이썬

import sys

def isOp(s):
    if(s=='+'or s=='-'or s=='*'or s=='/'):
        return True
    return False

for tc in range(1, 11):
    n=int(sys.stdin.readline())
    x=n//2
    res=1
    for i in range(n):
        node=sys.stdin.readline().split()
        k=int(node[0])
        j=node[1]
        if(k<=x):
            if not isOp(j):
                res=0
        else:
            if isOp(j):
                res=0
    print(f"#{tc} {res}")

자바

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class SWEA_1233 {
	
	static int x;
	static String a;


	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st;
		StringBuilder sb = new StringBuilder();
		
		for(int tc=1;tc<=10;tc++) {
			
			int n = Integer.parseInt(br.readLine());
			int k = n/2;
			int res=1;

			for(int i=0;i<n;i++) {

				String[] tree=br.readLine().split(" ");
				x=Integer.parseInt(tree[0]);
				a=tree[1];
				if(x<=n/2) {
					if(!isOp(a)) {
						res=0;
					}
				}
				else {
					if(isOp(a)) {
						res=0;
					}
					
				}
			}
			
			sb.append("#"+tc+" "+res+"\n");

		}
		System.out.println(sb);
	}
	
	public static boolean isOp(String s) {
	
		if(a.equals("-")||a.equals("+")||a.equals("*")||a.equals("/")) 
			return true;
		
		return false;
				
	}
}

💡 풀이

  • 완전 이진트리이므로 리프노드들은 숫자, 나머지 노드들은 연산자여야 연산이 가능하다
  • 전체 노드의 수를 n이라 했을 때 n//2+1노드까지는 자식 노드가 있고 그 후부터 모두 리프노드가 된다
  • 따라서 n//2+1번 노드까지 모두 연산자인지 확인, 나머지 노드들은 숫자인지 확인해주면 된다

0개의 댓글