문제
BOJ 1713 후보 추천하기
접근방법
- 조건이 많은 문제가 오히려 쉬울 때가 많다
- 조건 따라가면서 경우의 수 전개
- ArrayList 정렬 활용
- 여러 조건으로 정렬을 여러번 할 때, 마지막 정렬기준이 첫번째 분기 기준
구현
package DAY01.BOJ1713;
import java.nio.Buffer;
import java.util.*;
import java.io.*;
class Main {
static int N;
static int voteCnt;
static List<Candidate> frames;
public static void main(String [] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
N = Integer.parseInt(br.readLine());
voteCnt = Integer.parseInt(br.readLine());
frames = new ArrayList<>();
st = new StringTokenizer(br.readLine(), " ", false);
for (int i = 0; i < voteCnt; i++) {
int currVoteNum = Integer.parseInt(st.nextToken());
boolean isInFrames = false;
for (int j = 0 ; j<frames.size();j++){
if (frames.get(j).num == currVoteNum) {
frames.set(j, new Candidate(currVoteNum, frames.get(j).votesGot+1, frames.get(j).turn));
isInFrames = true;
break;
}
}
if (!isInFrames) {
if (frames.size() < N) frames.add(new Candidate(currVoteNum, 1, i));
else {
Collections.sort(frames, Comparator.comparing(Candidate::getTurn));
Collections.sort(frames, Comparator.comparing(Candidate::getVotesGot));
frames.set(0, new Candidate(currVoteNum, 1 ,i));
}
}
}
Collections.sort(frames, Comparator.comparing(Candidate::getNum));
for (int i = 0; i < frames.size(); i++) {
if (i == 0 ) System.out.print(frames.get(0).num + "");
else System.out.print(" " + frames.get(i).num);
}
}
}
class Candidate {
int num;
int votesGot;
int turn;
public Candidate(int num, int votesGot, int turn) {
this.num = num;
this.votesGot = votesGot;
this.turn = turn;
}
public int getNum() {
return num;
}
public int getVotesGot() {
return votesGot;
}
public int getTurn() {
return turn;
}
}
제출