반응형
문제 요약
직선상에 왼쪽부터 순서대로 1번부터 N번까지의 점이 있다. 1번 점에서 출반해서 N번 점까지 도착을 하는 것이 목적이다. 각 점 사이의 거리가 주어진다.
이 때, 각 점에서 사용할 수 있는 이동 수단이 있는데 각 이동 수단의 대기 시간과 거리를 1만큼 움직이는 데에 걸리는 시간이 각각 $p_i, s_i$가 주어진다.
이 때, 1번부터 N까지 가는 데에 걸리는 최소 시간을 구하여라.
풀이
다음과 같은 dp식을 유도해볼 수 있다.
$$
\begin{aligned}
dp(i) &= \text{1번부터 i번까지 가는 데에 걸리는 최소 시간} \\
dp(i) &= \underset{j<i}{min}(dp(j)+p_j+(d_i - d_j)*s_j)
\end{aligned}
$$
$d_i$는 1번부터 i번 까지의 거리를 뜻한다. 이 값을 prefix sum으로 쉽게 구할 수 있다.
$dp(N)$이 문제에서 원하는 값이 되는데 이를 구하기 위해서 나이브하게 계산하면 $O(N^2)$이 걸린다.
Convex Hull Trick을 사용하면 $O(NlogN)$으로 구할 수 있다. 기울기는 $s_j$로 보고 $x$값을 $d_i$로 보면 된다.
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
struct Line {
mutable ll k, m, p; // kx + m
bool operator<(const Line& o) const {
return k < o.k;
}
bool operator<(ll x) const { return p < x; }
};
struct LineContainer : multiset<Line, less<>> {
// (for doubles, use inf = 1/.0, div(a,b) = a/b)
const ll inf = LLONG_MAX;
ll div(ll a, ll b) { // floored division
return a / b - ((a ^ b) < 0 && a % b);
}
bool isect(iterator x, iterator y) {
if (y == end()) { x->p = inf; return false; }
if (x->k == y->k) x->p = x->m > y->m ? inf : -inf;
else x->p = div(y->m - x->m, x->k - y->k);
return x->p >= y->p;
}
void add(ll k, ll m) {
auto z = insert({ k, m, 0 }), y = z++, x = y;
while (isect(y, z)) z = erase(z);
if (x != begin() && isect(--x, y)) isect(x, y = erase(y));
while ((y = x) != begin() && (--x)->p >= y->p)
isect(x, erase(y));
}
ll query(ll x) {
assert(!empty());
auto l = *lower_bound(x);
return l.k * x + l.m;
}
};
int N;
ll dist[100005];
ll wait[100005], velo[100005];
ll ans[100005];
ll bias(int idx) {
return ans[idx] + wait[idx] - dist[idx] * velo[idx];
}
int main() {
cin.tie(nullptr); ios::sync_with_stdio(false);
cin >> N;
for (int i = 2; i <= N; ++i) {
ll x; cin >> x; dist[i] = dist[i - 1] + x;
}
for (int i = 1; i < N; ++i) cin >> wait[i] >> velo[i];
ans[1] = 0;
LineContainer lines;
lines.add(-velo[1], -bias(1));
for (int i = 2; i <= N; ++i) {
ll x = lines.query(dist[i]);
ans[i] = -x;
lines.add(-velo[i], -bias(i));
}
cout << ans[N] << '\n';
return 0;
}
반응형
'Problem Solving > 문제풀이' 카테고리의 다른 글
백준 14751번 Leftmost Segment (0) | 2021.02.15 |
---|---|
백준 5254번 Balls (0) | 2021.02.15 |
백준 6171번 땅따먹기 (0) | 2021.02.15 |
백준 13263번 나무 자르기 (0) | 2021.02.15 |
백준 15249번 Building Bridges (0) | 2021.02.15 |