Algorithms

[SWEA] 1232. 사칙연산 Java

devran 2023. 7. 19. 15:54
반응형

D4 - 도움많이받고품 ^^,,

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

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

//기본 클래스
public class Solution {

//사용할 Node 클래스 만들어줌 
	static class Node {
		int value;
		char opr;
		int left = -1, right = -1; 
		
		// 생성자
		public Node(int value, char opr, int left, int right) { 
			this.value = value;
			this.opr = opr;
			this.left = left;
			this.right = right;
		}
	} //end Node
	
	static int N; // 노드개수
	static int result; // 계산결과
	static Node[] nodes; // 위에 만들어준 Node 타입의 배열 선언
	
	public static void main(String args[]) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st;
		
		//10개의 테케 입력받기
		for (int test_case = 1; test_case <= 10; test_case++) {
			N = Integer.parseInt(br.readLine()); // 노드개수
			nodes = new Node[N + 1];//배열은 0부터 시작하지만, 노드는 1부터 시작하기 떄문
		
			/*
			 * 정점이 정수면 정점 번호와 양의 정수가 주어지고,
			 * 정점이 연산자이면 정점 번호, 연산자, 해당 정점의 왼쪽 자식, 오른쪽 자식의 정점 번호가 차례대로 주어진다.
			 */
			
			// 트리 입력받기
			for (int i = 1; i <= N; i++) { 
				st = new StringTokenizer(br.readLine(), " ");
				int nowNodeIdx = Integer.parseInt(st.nextToken());
				String valueOrOperator = st.nextToken(); //값인지 연산자인지 구분해줌
				
				//연산자 중 하나라면??
				if (valueOrOperator.equals("+") || valueOrOperator.equals("-") || valueOrOperator.equals("*") || valueOrOperator.equals("/")) {
					char opr = valueOrOperator.charAt(0);
					int left = Integer.parseInt(st.nextToken());
					int right = Integer.parseInt(st.nextToken());
					nodes[nowNodeIdx] = new Node(0, opr, left, right);
				} 
				
				// 값이라면?
				else {
					int value = Integer.parseInt(valueOrOperator);
					nodes[nowNodeIdx] = new Node(value, ' ', -1, -1);
				}
			}
			
			System.out.printf("#%d %d\\n", test_case, calc(nodes[1])); //트리의루트노드에서 부터 시작
		}
		
		br.close();
	}
	
///재귀적으로 호출하게 될 계산함수들
	private static int calc(Node node) {
		if (node.opr != ' ') {
			switch (node.opr) {
				case '+':
					return calc(nodes[node.left]) + calc(nodes[node.right]);
				case '-':
					return calc(nodes[node.left]) - calc(nodes[node.right]);
				case '*':
					return calc(nodes[node.left]) * calc(nodes[node.right]);
				case '/':
					return calc(nodes[node.left]) / calc(nodes[node.right]);
				default:
					return 0;
			}
		} else {
			return node.value;
		}
	}
}
반응형