728x90
더보기
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
for (int i = 0; i < 10; i++) {
vector<int> buildings;
vector<int> leftside;
int n, building;
cin >> n;
pair<int, int> side = { 0, 0 };
for (int j = 0; j < n; j++) {
cin >> building;
buildings.push_back(building);
leftside.push_back(building - max(side.first, side.second));
if (leftside.back() < 0) leftside.back() = 0;
side.second = side.first;
side.first = building;
}
int temp = 0, result = 0;
side = { 0, 0 };
for (int j = n-1; j >= 0; j--) {
temp = buildings[j] - max(side.first, side.second);
side.second = side.first;
side.first = buildings[j];
if (temp < 0) continue;
if (temp < leftside[j]) result += temp;
else result += leftside[j];
}
cout << "#" << i + 1 << " " << result << '\n';
}
return 0;
}
문제
https://swexpertacademy.com/main/code/problem/problemDetail.do
SW Expert Academy
SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!
swexpertacademy.com
728x90
[접근 1]
왼쪽이 막혔는지 확인하는 과정이다.
building의 높이를 받아오며 buildings에 저장해둔다.
pair에 바로 왼쪽에 있는 칸의 높이, 왼쪽으로 두번째에 있는 칸의 높이를 가지고 있다.
둘 중에 큰 값을 현재 위치의 빌딩의 높이에서 빼서 leftside라는 vector에 넣어준다.
그럼 leftside 벡터에는 왼쪽이 막혀있지 않은 칸의 수를 알 수 있다.
vector<int> buildings;
vector<int> leftside;
int n, building;
cin >> n;
pair<int, int> side = { 0, 0 };
for (int j = 0; j < n; j++) {
cin >> building;
buildings.push_back(building);
leftside.push_back(building - max(side.first, side.second));
if (leftside.back() < 0) leftside.back() = 0;
side.second = side.first;
side.first = building;
}
[접근 2]
같은 방법으로 오른쪽이 막혀있지 않은 칸의 수를 구하는 동시에
시간을 아끼기 위하여 leftside와 비교하여 더 적게 남은 칸의 수를 result에 더해준다.
int temp = 0, result = 0;
side = { 0, 0 };
for (int j = n-1; j >= 0; j--) {
temp = buildings[j] - max(side.first, side.second);
side.second = side.first;
side.first = buildings[j];
if (temp < 0) continue;
if (temp < leftside[j]) result += temp;
else result += leftside[j];
}728x90
'coding > algorithm' 카테고리의 다른 글
| [SW Expert Academy] D2 1859. 백만 장자 프로젝트(c++) (0) | 2022.05.18 |
|---|---|
| [SW Expert Academy] D1 2072. 홀수만 더하기(c++) (0) | 2022.05.18 |
| [programmers] Lv.1 실패율(c++) (0) | 2022.05.07 |
| [programmers] Lv.2 단체사진 찍기(c++) (0) | 2022.05.07 |
| [programmers] Lv.2 카카오프렌즈 컬러링북(c++) (0) | 2022.05.06 |
댓글