1. 程式人生 > >[USACO 2008 MAR] 土地購買

[USACO 2008 MAR] 土地購買

代碼 isdigit urn esp void \n target 關鍵字排序 tps

[題目鏈接]

https://www.lydsy.com/JudgeOnline/problem.php?id=1597

[算法]

首先將所有土地按長為第一關鍵字 , 寬為第二關鍵字排序

顯然 , 當i > j , 且yi >= yj時 , 土地j沒有用 , 不妨使用單調棧彈出所有沒有用的土地

用fi表示前i塊土地的最小經費

顯然 , fi = min{ fj + aibj }

斜率優化即可

時間復雜度 : O(N)

[代碼]

#include<bits/stdc++.h>
using
namespace std; #define N 50010 typedef long long ll; typedef long double ld; typedef unsigned long long ull; const ll inf = 1e18; struct info { ll x , y; } a[N]; ll n , l , r , top; ll f[N]; ll q[N] , X[N] , Y[N] , s[N]; template <typename T> inline void chkmax(T &x,T y) { x = max(x,y); } template
<typename T> inline void chkmin(T &x,T y) { x = min(x,y); } template <typename T> inline void read(T &x) { T f = 1; x = 0; char c = getchar(); for (; !isdigit(c); c = getchar()) if (c == -) f = -f; for (; isdigit(c); c = getchar()) x = (x << 3) + (x << 1
) + c - 0; x *= f; } inline bool cmp(info a , info b) { if (a.x != b.x) return a.x < b.x; else return a.y < b.y; } int main() { read(n); for (int i = 1; i <= n; i++) { read(a[i].x); read(a[i].y); } sort(a + 1 , a + n + 1 , cmp); for (int i = 1; i <= n; i++) { while (top > 0 && a[i].y >= a[s[top]].y) --top; s[++top] = i; } for (int i = 0; i < top; i++) X[i] = -a[s[i + 1]].y; q[f[l = r = 1] = 0] = 0; for (int i = 1; i <= top; i++) { while (l < r && Y[q[l + 1]] - Y[q[l]] <= a[s[i]].x * (X[q[l + 1]] - X[q[l]])) ++l; f[i] = f[q[l]] - a[s[i]].x * X[q[l]]; Y[i] = f[i]; while (l < r && (Y[i] - Y[q[r]]) * (X[q[r]] - X[q[r - 1]]) <= (Y[q[r]] - Y[q[r - 1]]) * (X[i] - X[q[r]])) --r; q[++r] = i; } printf("%lld\n" , f[top]); return 0; }

[USACO 2008 MAR] 土地購買