문제
신호등의 개수(N), 도로의 길이(L)가 주어져 있으며 각 신호등의 도로 위의 위치와 빨간불, 초록불이 유지되는 시간이 주어져 있다. 트럭이 1초에 1m씩 이동하고, 신호를 지켜 도로(Lm)를 다 지나갈 때 몇 초가 걸리는지 계산하는 문제.
접근방법
신호등 데이터를 도로 배열에 저장한다.
Traffic_light라는 클래스를 새로 만들고, 여기에는 빨간불 유지 시간(R), 초록불 유지시간(G)를 가지고 있다.
Traffic_light를 타입으로 하는 배열을 선언하고, 신호등의 위치(D)에 신호등 데이터(R, G)를 저장한다.
load[D] = new Traffic_light(R, G)
일정한 규칙으로 반복되는 신호등이 x초일 때 얼마나 기다려야 하는지를 계산한다.
나머지 연산을 이용해 계산한다.
예를 들어 (4, 2)로 반복되는 신호등은 xxxxoo가 반복되는데 time=7인 경우에는 7%6로 해서 첫번째 x에 해당된다.
남은 시간을 계산할 때에는 전체 R에서 7%6인 1을 뺀 값을 더해준다. 즉, 3초를 기다리므로 3을 더해준다.
소스코드
static class Traffic_light{
int R; int G;
public Traffic_light(int r, int g) {this.R = r; this.G = g;}
}
public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String[] input = in.readLine().split(" ");
int N = Integer.parseInt(input[0]);
int L = Integer.parseInt(input[1]);
// 도로 위 신호등 확인 배열
Traffic_light[] load = new Traffic_light[L+1];
for(int i=0; i<N; i++){
String[] input_data = in.readLine().split(" ");
int D = Integer.parseInt(input_data[0]);
int R = Integer.parseInt(input_data[1]);
int G = Integer.parseInt(input_data[2]);
load[D] = new Traffic_light(R, G);
}
int time = 0;
int pos = 0;
while(pos < L){
++time; //시간초 증가
++pos; // 다음 위치로 이동
// 다음에 이동할 곳에 신호등이 있는 경우
if(load[pos] != null){
int check = time % (load[pos].R + load[pos].G);
// 현재 빨간불인 경우 기다렸다가 지나감
if(check <= load[pos].R){
time += (load[pos].R - check);
}
}
}
System.out.println(time);
}
'알고리즘' 카테고리의 다른 글
[JAVA] 백준 3985 : 롤케이크 (0) | 2019.02.01 |
---|---|
[JAVA] 백준 10610 : 30 (0) | 2019.02.01 |
[JAVA] 백준 2593 : 영역 구하기 (0) | 2019.01.20 |
[JAVA] 백준 1018 : 체스판 다시 칠하기 (0) | 2019.01.16 |
[JAVA] 백준 1120 : 문자열 (0) | 2019.01.13 |