Created
August 6, 2020 23:02
-
-
Save cgiosy/37e499ebf3ec809519bf01c678ecf9ce to your computer and use it in GitHub Desktop.
간단하고 짧고 범용성 있는 Li-Chao Tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <bits/stdc++.h> | |
using namespace std; | |
using ll=long long; | |
constexpr int MXN=1e5; | |
int A[MXN], B[MXN], N; | |
ll D[MXN]; | |
ll f(int j, int i) { return D[j] + 1LL*A[i]*B[j]; } | |
bool cmp(int i, int j, int x) { return f(i, x)<f(j, x); } | |
struct node { int v, l, r; } T[MXN]; | |
int id=1; | |
void add(int a) { | |
int s=1, e=N-1, i=1; | |
while(i) { | |
int m=s+e>>1, &b=T[i].v; | |
if(cmp(a, b, m)) swap(a, b); | |
if(cmp(a, b, s)) e=m-1, i=T[i].l=T[i].l?:++id; | |
else if(cmp(a, b, e)) s=m+1, i=T[i].r=T[i].r?:++id; | |
else break; | |
} | |
} | |
int qry(int x) { | |
int s=1, e=N-1, i=1, a=0; | |
while(i) { | |
int m=s+e>>1, b=T[i].v; | |
if(cmp(b, a, x)) a=b; | |
if(x<m) e=m-1, i=T[i].l; | |
else if(x>m) s=m+1, i=T[i].r; | |
else break; | |
} | |
return a; | |
} | |
int main() { | |
ios::sync_with_stdio(0);cin.tie(0); | |
cin>>N; | |
for(int i=0; i<N; i++) cin>>A[i]; | |
for(int i=0; i<N; i++) cin>>B[i]; | |
for(int i=1; i<N; i++) { | |
add(i-1); | |
D[i]=f(qry(i), i); | |
} | |
cout<<D[N-1]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
설명
구현
f(j, i)
는 사용자가 직접 코드를 짜야 한다. 위 예시에서는 나무 자르기의 DP식을 써넣었다.<
면 최소,>
면 최대를 구한다.qry(x)
=x
에서 최소/최대인 함수의 인덱스를 구한다.f(qry(x), x)
처럼 쓴다.add(a)
= 인덱스가a
인 함수을 트리에 추가한다.참고
a ?: b
는 GCC 및 Clang의 비표준 문법으로,a ? a : b
와 같은 의미이다.