본문 바로가기
알고리즘/프로그래머스 문제

[ALGORITHM] LEVEL3 2022 KAKAO BLIND RECRUITMENT - 파괴되지 않은 건물

by HDobby 2022. 12. 28.

https://school.programmers.co.kr/learn/courses/30/lessons/92344

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

생각해보기

  • 단순히 N*M*skill 로 한다면 효율성에서 1000*1000*250'000 이 되므로 통과하지 못한다.
  • 모든 칸에 정보를 저장할 필요는 없다. O(N+M)으로 구하는 방법을 생각해보자.
  • 구간합(Prefix Sum)만을 따로 구하는 알고리즘을 찾아보자.

코드

더보기
#include <string>
#include <vector>
#include <iostream>

using namespace std;

int presum[1111][1111];
int N,M;

int calc(vector<vector<int>>& board, vector<vector<int>>& skill){
    for(int i=0,sz=skill.size();i<sz;++i){
        int r1=skill[i][1];
        int c1=skill[i][2];
        int r2=skill[i][3];
        int c2=skill[i][4];
        int degree=skill[i][0]==1?-skill[i][5]:skill[i][5];
        
        presum[r1][c1]+=degree;
        presum[r2+1][c1]-=degree;
        presum[r1][c2+1]-=degree;
        presum[r2+1][c2+1]+=degree;
    }
    
    for(int i=1;i<=N;++i){
        for(int j=0;j<M;++j){
            presum[i][j]+=presum[i-1][j];
        }
    }
    
    for(int j=1;j<=M;++j){
        for(int i=0;i<N;++i){
            presum[i][j]+=presum[i][j-1];
        }
    }
    
    int answer=0;
    for(int i=0;i<N;++i){
        for(int j=0;j<M;++j){
            if(presum[i][j]+board[i][j]>0)
                ++answer;
        }
    }
    return answer;
}

int solution(vector<vector<int>> board, vector<vector<int>> skill) {
    int answer = 0;
    
    N = board.size();
    M = board[0].size();
    
    answer = calc(board, skill);
    
    return answer;
}

참고

728x90

댓글