-
카테고리
-
세부 분야
알고리즘 · 자료구조
-
해결 여부
미해결
9-3. 결혼식 질문있습니다.
23.10.29 17:27 작성 조회수 153
0
import java.util.*;
import java.io.*;
class Main {
static int N;
static class Time implements Comparable<Time>{
int time;
char state;
Time (int time, char state) {
this.time = time;
this.state = state;
}
public int compareTo(Time t) {
if(time > t.time) {
return 1;
}else if(time == t.time) {
if(state != t.state && t.state == 'e') {
return 1;
}
}
return -1;
}
}
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
N = Integer.parseInt(br.readLine());
ArrayList<Time> guests = new ArrayList<>();
for(int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
int start = Integer.parseInt(st.nextToken());
int end = Integer.parseInt(st.nextToken());
guests.add(new Time(start, 's'));
guests.add(new Time(end, 'e'));
}
Collections.sort(guests);
System.out.println(solution(guests));
}
public static int solution(ArrayList<Time> guests) {
int ans = 0;
int cnt = 0;
for(Time t : guests) {
if(t.state == 's') {
cnt++;
ans = Math.max(ans, cnt);
} else {
cnt--;
}
}
return ans;
}
}
제가 작성한 코드는 위와 같습니다. 강의에서 나온 코드와 거의 흡사한데 채점을 하면 런타임 에러가 발생합니다. 무슨 문제일까요?
감사합니다.
답변을 작성해보세요.
0
김태원
지식공유자2023.10.31
안녕하세요^^
Time 클래스의 비교 메서드인 compateTo 를 바꾸니까 되네요. 이유는 저도 잘 모르겠습니다.
import java.util.*;
import java.io.*;
class Main {
static int N;
static class Time implements Comparable<Time>{
int time;
char state;
Time (int time, char state) {
this.time = time;
this.state = state;
}
@Override
public int compareTo(Time ob){
if(this.time==ob.time) return this.state-ob.state;
else return this.time-ob.time;
}
}
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
N = Integer.parseInt(br.readLine());
ArrayList<Time> guests = new ArrayList<>();
for(int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
int start = Integer.parseInt(st.nextToken());
int end = Integer.parseInt(st.nextToken());
guests.add(new Time(start, 's'));
guests.add(new Time(end, 'e'));
}
Collections.sort(guests);
System.out.println(solution(guests));
}
public static int solution(ArrayList<Time> guests) {
int ans = 0;
int cnt = 0;
for(Time t : guests) {
if(t.state == 's') {
cnt++;
ans = Math.max(ans, cnt);
} else {
cnt--;
}
}
return ans;
}
}
답변 1