알고리즘

[JAVA/자바] 백준 BAEKJOON 3048번 개미

remazitensi 2024. 8. 18. 00:53

문제링크

https://www.acmicpc.net/problem/3048

문제 풀이

두 그룹의 개미가 서로 반대 방향으로 이동하며, 개미가 만나면 점프하여 위치를 바꾸는 과정을 T초 동안 반복하는 것입니다. 먼저 두 그룹의 개미 수를 입력받고, 각 그룹의 개미 순서를 리스트에 저장합니다. 첫 번째 그룹의 개미는 역순으로 추가하여 리스트의 앞쪽에 위치하게 하고, 두 번째 그룹의 개미는 순서대로 추가합니다. 이후 T초 동안 리스트를 순회하며 서로 다른 그룹의 개미를 발견할 때마다 위치를 교환하고, 교환 후 인덱스를 하나 건너뛰어 다음 비교를 진행합니다. 마지막으로 최종 개미 순서를 출력합니다.

 

코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;

public class BJ_3048 {
    static ArrayList<Ant> list = new ArrayList<>();

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        int N1 = Integer.parseInt(st.nextToken());
        int N2 = Integer.parseInt(st.nextToken());
        String s1 = br.readLine();
        String s2 = br.readLine();
        int T = Integer.parseInt(br.readLine());

        // 첫 번째 그룹 개미 추가 (역순으로)
        for (int i = s1.length() - 1; i >= 0; i--) {
            list.add(new Ant(s1.charAt(i), 1));
        }
        // 두 번째 그룹 개미 추가
        for (int i = 0; i < s2.length(); i++) {
            list.add(new Ant(s2.charAt(i), 2));
        }

        // T초 반복
        while (T-- > 0) {
            for (int i = 0; i < list.size() - 1; i++) {
                Ant now = list.get(i);
                Ant next = list.get(i + 1);
                // 서로 다른 그룹의 개미일 경우 교환
                if (now.num != next.num) {
                    list.set(i, next);
                    list.set(i + 1, now); // 위치 변경
                    i++; // 한 번 교환하면 건너뛰기
                }
            }
        }

        // 결과 출력
        for (Ant ant : list) {
            System.out.print(ant.ch);
        }
    }

    public static class Ant {
        char ch;
        int num;

        public Ant(char ch, int num) {
            this.ch = ch;
            this.num = num;
        }
    }
}