본문 바로가기
Problem Solving/Baekjoon

[백준] 20651 Daisy Chains - Brute Force / Java

by graycode 2023. 10. 29.

 문제 링크

 

20651번: Daisy Chains

Every picture containing just a single flower contributes to the count (there are four of these in the example). Also, the $(i,j)$ ranges $(1,2)$ and $(2,4)$ in this example correspond to pictures that have an average flower.

www.acmicpc.net

 

 풀이 코드

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class Main {

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

        int[] arr = new int[read()];
        for (int i = 0; i < arr.length; i++) arr[i] = read();

        int cnt = 0;
        for (int i = 0; i < arr.length; i++) {
            for (int j = i; j < arr.length; j++) {
                int sum = 0;
                for (int k = i; k <= j; k++) sum += arr[k];

                if (sum % (j - i + 1) != 0) continue;
                int avg = sum / (j - i + 1);

                for (int k = i; k <= j; k++) {
                    if (avg == arr[k]) {
                        cnt++;
                        break;
                    }
                }
            }
        }

        bw.write(String.valueOf(cnt));
        bw.flush();
    }

    private static int read() throws IOException {
        int c, n = System.in.read() & 15;
        while ((c = System.in.read()) > 32) n = (n << 3) + (n << 1) + (c & 15);

        return n;
    }

}

댓글