[프로그래머스] 카펫

hamsteak·2023년 9월 20일
0

ps

목록 보기
13/39

갈색격자와 노란색격자의 개수가 각각 주어졌을 때, 가로와 세로 길이를 구하는 문제.

갈색 격자의 개수는 테두리 길이의 합이고 노란색 격자의 개수는 총 격자 개수에서 테두리격자 개수만큼 뺀 것이므로 다음과 같은 식을 얻을 수 있다.

brown=2Width+2Height4brown = 2*Width + 2*Height - 4
yellow=WidthHeightbrownyellow = Width * Height - brown

가로 길이에 1부터 최댓값인 테두리의 절반까지 넣어보며 가능한 경우의 수를 찾아주면 된다.

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

cpp code

#include <string>
#include <vector>

using namespace std;

vector<int> solution(int brown, int yellow) {
    vector<int> answer;
    
    for (int w=1; w<=brown/2; w++) {
        int h = (brown - w * 2 + 4) / 2;
        if (w * h - brown == yellow) {
            if (h > w) { int t=w;w=h;h=t; }
            answer.push_back(w);
            answer.push_back(h);
            break;
        }
    }
    
    return answer;
}
profile
안녕하세요

0개의 댓글