728x90
https://www.acmicpc.net/problem/13305
13305번: 주유소
표준 입력으로 다음 정보가 주어진다. 첫 번째 줄에는 도시의 개수를 나타내는 정수 N(2 ≤ N ≤ 100,000)이 주어진다. 다음 줄에는 인접한 두 도시를 연결하는 도로의 길이가 제일 왼쪽 도로부터 N-1
www.acmicpc.net
접근 방법
예제 1을 살펴보자.

여기서 중요한 점을 체크해봤다.
1. 첫번째 도시에선 무조건 기름을 구입해야한다.
2. 마지막 도시의 기름값은 무시한다.
3. 현재 도시에서 다음 도시들 중 현재 도시의 기름값보다 싼 도시까지 가는 기름만 구매한다.
(2에서 4를 거쳐 1로 가는 과정에서 2보다 싼 도시까지가는 거리의 기름을 산다.)
예를 들어 2 4 5 1 3 이런 도시가 있다고할 때,
2에서 1까지 가는 거리만큼 기름을 사야한다.
코드
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
#define MAX 100001
int n;
long long price[MAX];
long long distances[MAX];
long long totalPrice;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n;
for (int i = 0; i < n - 1; i++)
cin >> distances[i];
for (int i = 0; i < n; i++)
cin >> price[i];
int idx = 0;
while (idx < n-1) {
long long currPrice = price[idx];
long long totalDis = distances[idx];
int i = idx + 1;
//cout << "currPrice: " << currPrice << " , price[i]: " << price[i] << endl;
for (; currPrice <= price[i]; i++) {
//cout << "currPrice: " << currPrice << " , price[i]: " << price[i] << endl;
totalDis += distances[i];
}
totalPrice += (totalDis * currPrice);
//cout << "totalPrice: " << totalPrice << endl << endl;
idx = i;
}
cout << totalPrice;
}

728x90
'📊알고리즘 > BOJ' 카테고리의 다른 글
[그리디 #9] BOJ 11508 - 2+1 세일 (0) | 2024.02.11 |
---|---|
[그리디 #8] BOJ 1758 - 알바생 강호 (0) | 2024.02.11 |
[그리디 #6] BOJ 1343 - 폴리오미노 (0) | 2024.02.10 |
[그리디 #5] BOJ 14916 - 거스름돈 (0) | 2024.02.09 |
[그리디 #4] BOJ 1744 - 수 묶기 (1) | 2024.02.07 |