SW Expert Academy
SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!
swexpertacademy.com
1. 내 코드
import java.util.*;
class Solution
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int test_case = 1; test_case <= T; test_case++) {
int N = sc.nextInt();
int speed = 0;
int totalDistance= 0;
// 첫번째 입력에 따라 두번째 입력의 부호가 결정됨.
// 0일 경우 두 번째 입력이 주어지지 않는다.
// N 뒤에 입력이 무조건 2*N은 아니지만, line은 N개가 맞다.
sc.nextLine();
// N개의 String 배열을 만들어, 그 안에 입력 값들을 집어 넣는다.
String[] str = new String[N];
// 원소를 모두 split(" ")으로 찢어서 새로운 스트링 배열에 넣고,
// 새로운 스트링 배열의 첫 원소에 따라 두번째 원소의 부호를 정해서 speed에 더한다. -> 가속력 오르내림 표현
// 거리 = 속력 *시간, 시간은 1초로 default로 정해져 있으므로, 거리 = 그때 그때의 속력을 더해주면 된다.
for (int i = 0; i < N; i++) {
str[i] = sc.nextLine();
String[] splitString = str[i].split(" ");
if(splitString[0].equals("1")){
speed += Integer.parseInt(splitString[1]);
totalDistance += speed;
} else if (splitString[0].equals("2")) {
// 만약 속도가 이미 0이라면 가속도가 감속이어도 speed에서 빼지 않는다.
if(speed != 0) {
speed -= Integer.parseInt(splitString[1]);
}
totalDistance += speed;
} else if (splitString[0].equals("0")) {
// 가속도에 변동이 없다면 이전속도 그대로 더해버린다.
totalDistance += speed;
}
}
System.out.printf("#%d %d\n", test_case, totalDistance);
}
}
}
내 코드가 살짝 코드 수가 많은 편이어서 코드 수가 적은 다른 사람의 것도 확인해보았다.
2. 다른 사람 코드
import java.util.Scanner;
class Solution
{
public static void main(String args[]) throws Exception
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for(int i=0; i<t; i++){
int n = sc.nextInt();
int speed = 0;
int result = 0;
for(int j=0; j<n; j++){
int mode = sc.nextInt();
if(mode==1){
speed += sc.nextInt();
}
else if(mode==2){
//max함수는 인자로 받은 두 값 중 최대인 값을 반환한다.
speed = (int)Math.max(speed - sc.nextInt(),0);
}
result += speed;
}
System.out.printf("#%d %d\n",i+1,result);
}
}
}
나는 testcase마다 N이 주어져도, 그 반복횟수가 일정치 않아서 값을 sc.nextLine()으로 받아서 쪼개 활용하였으나,
이 분 같은 경우, 만약 가속도인 첫 입력이 1이나 2일 경우 그 다음 입력까지 신경쓰고 그게 아니라면 입력을 신경쓰지 않았다. 이렇게 하면 입력값이 testcase마다 일정치 않아도 상관없이 문제를 풀 수 있다.
굳이 N번 반복하는 반복문에 값을 넣어 풀어야겠다는 생각을 깨주어서 고맙다.
그 다음은 Max라는 함수를 이용해, 내가 if문을 쓴 것보다 코드 수를 절약한 것 같다.
0