알고리즘/알고리즘 문제풀이

[프로그래머스] 161989 : 덧칠하기 / SegFault(Core dumped) 에러

mint* 2023. 11. 29. 10:53
728x90

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

 

프로그래머스

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

programmers.co.kr

 

SegFault(Core dumped) 발생한 코드

#include <bits/stdc++.h>

using namespace std;
bool colored[100004];

int solution(int n, int m, vector<int> section) {
    int answer = 0;
    //1. section 시작점부터 m칸 색칠
    for(int i=0;i<section.size();i++){
        int start = section[i];
        if (colored[start]==1) continue;
        for(int j=start;j<start+m;j++){
            colored[j]=true;  
        } 
        answer++;
    }
    return answer;
}

위 코드에서 colored[j] 접근시에 start+m-1이 colored 초기화 범위를 벗어나므로 에러가 발생한다.

✅ 배열 접근시 범위 확인

 

해결 코드

#include <bits/stdc++.h>

using namespace std;
bool colored[100004];

int solution(int n, int m, vector<int> section) {
    int answer = 0;
    //1. section 시작점부터 m칸 색칠
    for(int i=0;i<section.size();i++){
        int start = section[i];
        if (colored[start]==1) continue;
        for(int j=start;j<min(start+m, n+1);j++){
            colored[j]=true;  
        } 
        answer++;
    }
    return answer;
}

 

배열에 접근할 수 있는 인덱스 범위를 제한한다.

for(int j=start;j<min(start+m, n+1);j++){
    colored[j]=true;  
}

 

 

모범 코드

int pivot=section[0];
for(auto s:section){
    if(s<pivot+m) continue;
    else {
        pivot=s;
        answer++;
    }
}

pivot을 사용해 기준점을 정하고, 색칠되지 않은 부분으로 이동한다.

(한창균님 풀이)

https://school.programmers.co.kr/learn/courses/30/lessons/161989/solution_groups?language=cpp

 

프로그래머스

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

programmers.co.kr

 

728x90