๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Algorithm

[Algorithm/Java][๋ฐฑ์ค€] 1806๋ฒˆ ๋ถ€๋ถ„ํ•ฉ

๋ฐ˜์‘ํ˜•

[BOJ] 1806๋ฒˆ ๋ถ€๋ถ„ํ•ฉ

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

๋ฌธ์ œ ์ ‘๊ทผ

ํˆฌ ํฌ์ธํ„ฐ๋ฅผ ์ด์šฉํ•ด์„œ ๋ฌธ์ œ๋ฅผ ํ’€์—ˆ๋‹ค.
deque์™€ ์ด๋ถ„ ํƒ์ƒ‰์„ ์ด์šฉํ•ด์„œ๋„ ํ’€ ์ˆ˜ ์žˆ๋‹ค๊ณ  ํ•˜๋Š”๋ฐ ๋ถ„๋ฅ˜๊ฐ€ ํˆฌ ํฌ์ธํ„ฐ๋ผ์„œ ํˆฌ ํฌ์ธํ„ฐ๋ฅผ ์‚ฌ์šฉํ•ด์„œ ํ’€์—ˆ๋‹ค.
start์™€ end์ธ ๋‘ ๊ฐœ์˜ ์ธ๋ฑ์Šค๋ฅผ ์‚ฌ์šฉํ•˜๊ณ  sum์ด t(๋ชฉํ‘œ ๊ฐ’)๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์œผ๋ฉด end๋ฅผ +1ํ•ด์„œ ํ•œ๊ฐœ๋ฅผ ๋” ๋”ํ•˜๋„๋ก ํ•˜๊ณ , sum์ด t(๋ชฉํ‘œ ๊ฐ’)๋ณด๋‹ค ํฌ๋ฉด start๋ฅผ +1 ํ•ด์„œ ํ•ฉ์—์„œ ํ•œ๊ฐœ๋ฅผ ๋นผ์„œ ๋ชฉํ‘œ ๊ฐ’์— ์ ‘๊ทผํ•˜๋„๋ก ํ•œ๋‹ค.
ํˆฌ ํฌ์ธํ„ฐ๋ฅผ ์‚ฌ์šฉํ•˜๊ฒŒ ๋˜๋ฉด O(N)์œผ๋กœ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๊ฒŒ ๋˜๋Š” ์žฅ์ ์ด ์žˆ๋‹ค.

Code

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

public class BOJ1806 {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        int n = Integer.parseInt(st.nextToken());
        int t = Integer.parseInt(st.nextToken());
        int[] arr = new int[n];
        st = new StringTokenizer(br.readLine());
        for(int i =0; i<n; i++){
            arr[i] = Integer.parseInt(st.nextToken());
        }
        int start = 0;
        int end = 0;
        int sum = arr[0];
        int answer = Integer.MAX_VALUE;
        while(start<=end){
            if(sum >= t){
                answer = Math.min(answer, end - start + 1);
            }
            if(sum <= t){
                end++;
                if(end == n) break;
                sum += arr[end];
            } else {
                sum -= arr[start];
                start++;
                if(start == n) break;
            }
        }
        if(answer == Integer.MAX_VALUE) System.out.println(0);
        else System.out.println(answer);
    }
}
๋ฐ˜์‘ํ˜•