1. 程式人生 > >[BZOJ1579][Usaco2008 Mar]土地購買

[BZOJ1579][Usaco2008 Mar]土地購買

mem esc str com col 希望 per blog usaco2008

1597: [Usaco2008 Mar]土地購買

Time Limit: 10 Sec Memory Limit: 162 MB
Submit: 5094 Solved: 1887
[Submit][Status][Discuss]

Description

農夫John準備擴大他的農場,他正在考慮N (1 <= N <= 50,000) 塊長方形的土地. 每塊土地的長寬滿足(1 <= 寬 <= 1,000,000; 1 <= 長 <= 1,000,000). 每塊土地的價格是它的面積,但FJ可以同時購買多快土地. 這些土地的價格是它們最大的長乘以它們最大的寬, 但是土地的長寬不能交換. 如果FJ買一塊3x5的地和一塊5x3的地,則他需要付5x5=25. FJ希望買下所有的土地,但是他發現分組來買這些土地可以節省經費. 他需要你幫助他找到最小的經費.

Input

* 第1行: 一個數: N

* 第2..N+1行: 第i+1行包含兩個數,分別為第i塊土地的長和寬

Output

* 第一行: 最小的可行費用.

Sample Input

4
100 1
15 15
20 5
1 100

輸入解釋:

共有4塊土地.

Sample Output

500 若一塊土地x,y均不比另一塊的大,那麽可以順便買了,對答案沒有影響,去掉 剩下的土地排成x增y減,設$dp[i]$表示買下前i塊土地的最小花費,則$dp[i]=min(dp[j]+y[j+1]*x[i]) (0<=j<i)$,顯然斜率優化
#include <cstdio>
#include 
<algorithm> using namespace std; const int maxn = 50000 + 10; typedef long long ll; struct Node{ int x, y; bool operator < (const Node &a) const { return x != a.x ? x < a.x : y < a.y; } }no[maxn]; int x[maxn], y[maxn], cnt; ll dp[maxn]; double slope(int a, int b){
return (double)(dp[a] - dp[b]) / (y[a + 1] - y[b + 1]); } int q[maxn], h, t; int main(){ int n; scanf("%d", &n); for(int i = 1; i <= n; i++) scanf("%d %d", &no[i].x, &no[i].y); sort(no + 1, no + n + 1); cnt = 1; x[1] = no[1].x; y[1] = no[1].y; for(int i = 2; i <= n; i++){ while(cnt && no[i].y >= y[cnt]) cnt--; cnt++; x[cnt] = no[i].x; y[cnt] = no[i].y; } dp[0] = 0; q[h = t = 1] = 0; for(int i = 1; i <= cnt; i++){ while(h < t && slope(q[h], q[h + 1]) > -x[i]) h++; dp[i] = dp[q[h]] + (ll)y[q[h] + 1] * x[i]; while(h < t && slope(q[t - 1], q[t]) < slope(q[t], i)) t--; q[++t] = i; } printf("%lld\n", dp[cnt]); return 0; }

[BZOJ1579][Usaco2008 Mar]土地購買