알고리즘 문제
백준 5002 도어맨 java greedy
veryhi
2022. 9. 9. 10:34
https://www.acmicpc.net/problem/5002
5002번: 도어맨
첫째 줄에 정인이가 기억할 수 있는 가장 큰 차이 X<100이 주어진다. 둘째 줄에는 줄을 서 있는 순서가 주어진다. W는 여성, M은 남성을 나타내며, 길이는 최대 100이다. 가장 왼쪽에 있는 글자가 줄
www.acmicpc.net
참고:
1. 문자열을 일일이 수정하는 데에 있어서 StringBuilder의 setCharAt 메서드를 활용했었다.
2. 그래서 문자열을 애시당초 StringBuilder로 받았었다.
3. 왜 스택을 썼는지 모르겠지만, 스택으로 받아서 넣었었다. 그냥 갯수만 세도 되니까 사실 굳이 쓰지 않아도 된다.
4. 문제 풀다가 앞서 갱신한 tempCount를 그대로 활용했다가 큰일날 뻔 했었다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
StringBuilder people = new StringBuilder(br.readLine());
int manCount=0, womanCount=0;
Stack<Character> stack = new Stack<>();
for(int i=0; i<people.length(); ++i){
boolean sexCheck = people.charAt(i) == 'M'; // 삼항 연산 필요 없음
int tempCount;
int diff;
if(sexCheck){ // man
tempCount = manCount + 1;
diff = Math.abs(tempCount - womanCount);
}
else{ // woman
tempCount = womanCount + 1;
diff = Math.abs(tempCount - manCount);
}
if(n < diff){ // 남녀차가 n보다 크다
int iPlus1 = i+1; // 다음 사람 미리보기
if(iPlus1 < people.length()){ // 인덱스 범위 안이다.
if(people.charAt(iPlus1) != people.charAt(i)){
stack.push(people.charAt(iPlus1));
char temp = people.charAt(iPlus1);
people.setCharAt(iPlus1, people.charAt(i));
people.setCharAt(i, temp);
if(sexCheck) ++womanCount;
else ++manCount;
}
else break;
}
else break;
}
else { // 범위 안에 들어오면 그냥 추가
stack.push(people.charAt(i));
if(sexCheck) manCount = tempCount;
else womanCount = tempCount;
}
}
System.out.print(stack.size());
}
}