백준 28292번 개미 수열 Java

: ) YOUNG·2025년 9월 22일
1

알고리즘

목록 보기
489/489
post-thumbnail

백준 28292번 개미 수열 Java

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

문제



생각하기




동작



결과


코드



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

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());

        // N=1, 2일 때는 가장 큰 수가 1
        if (N <= 2) {
            System.out.println(1);
        // N=3, 4, 5일 때는 2가 처음 등장하고 가장 큼
        } else if (N <= 5) {
            System.out.println(2);
        // N=6부터는 3이 등장하고 항상 가장 큼
        } else {
            System.out.println(3);
        }
    }
}


개미수열 구현 (정답 아님 주의)


import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {

    // input
    private static BufferedReader br;

    public static void main(String[] args) throws IOException {
        br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        bw.write(solve());
        bw.close();
    } // End of main()

    private static String solve() throws IOException {
        StringBuilder sb = new StringBuilder();

        int N = Integer.parseInt(br.readLine());
        if (N <= 2) {
            sb.append(1);
            return sb.toString();
        }

        List<Integer> list = new ArrayList<>();
        int ans = 1;
        list.add(1);

        for (int i = 1; i < N; i++) {
            int size = list.size();
            List<Integer> nextList = new ArrayList<>();
            int target = list.get(0);
            int count = 1;

            for (int j = 1; j < size; j++) {
                if (list.get(j) == target) {
                    count++;
                } else {
                    nextList.add(target);
                    nextList.add(count);
                    target = list.get(j);
                    count = 1;
                }
            }

            nextList.add(target);
            nextList.add(count);
            list = nextList; // 다음 항으로 리스트 교체
        }

        ans = Collections.max(list);
        sb.append(ans);
        return sb.toString();
    } // End of solve()
} // End of Main class

0개의 댓글