문제 풀이/소프티어

[소프티어] 나무 공격(JAVA)

27200 2025. 2. 16. 16:18

문제

https://softeer.ai/practice/9657


풀이(11분)

import java.io.*;
import java.util.*;

public class Main {
    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 m = Integer.parseInt(st.nextToken()); // 열 입력

        int[] people = new int[n]; // 라인 별 사람의 수
        int totalPeople = 0; // 총 사람의 수

        for(int i = 0; i < n; i++){
            st = new StringTokenizer(br.readLine());
            int linePeople = 0;
            for(int j = 0; j < m; j++){
                if(Integer.parseInt(st.nextToken()) == 1){ // 사람이 있다면
                    totalPeople++;
                    linePeople++;
                }
            }
            people[i] = linePeople;
        }

        for(int i = 0; i < 2; i++){
            st = new StringTokenizer(br.readLine());
            int l = Integer.parseInt(st.nextToken()) - 1; // l 라인
            int r = Integer.parseInt(st.nextToken()) - 1; // r 라인
            for(int j = l; j <= r; j++){
                if(people[j] > 0){ // 환경파괴범이 있다면
                    totalPeople--; 
                    people[j]--;
                }
            }
        }

        System.out.println(totalPeople);
    }
}

 

배열을 굳이 저장하지 않고, 행 별로 사람이 얼마나 있는지만 확인해 주면 되는 문제였다.

 

행마다 사람이 얼마나 있는지를 저장하고, 총 10번의 반복을 통해 (전체 사람의 수) - 1을 진행해 주면 된다.

 

이때 주의할 점은 라인에 사람이 있는지 없는지 확인하고 해주어야 한다는 것이다.