您的位置:首页 > 其它

【BZOJ1597】【USACO 2008 Mar】土地购买(斜率优化DP)

2018-01-07 20:18 495 查看

Description

click me

Solution

首先按x进行排序,并排除可以包含的土地,然后发现可以dp:dpi=dpj+xi×yj+1

斜率优化到O(n)即可。

Code

/**************************
Au: Hany01
Date: Jan 7th, 2018
Prob: bzoj1597 & usaco2008 Mar
Email: hany01@foxmail.com
**************************/

#include<bits/stdc++.h>

using namespace std;

typedef long long LL;
typedef pair<int, int> PII;
#define rep(i, j) for (register int i = 0, i##_end_ = (j); i < i##_end_; ++ i)
#define For(i, j, k) for (register int i = (j), i##_end_ = (k); i <= i##_end_; ++ i)
#define Fordown(i, j, k) for (register int i = (j), i##_end_ = (k); i >= i##_end_; -- i)
#define Set(a, b) memset(a, b, sizeof(a))
#define Cpy(a, b) memcpy(a, b, sizeof(a))
#define fir first
#define sec second
#define pb(a) push_back(a)
#define mp(a, b) make_pair(a, b)
#define ALL(a) (a).begin(), (a).end()
#define SZ(a) ((int)(a).size())
#define INF (0x3f3f3f3f)
#define INF1 (2139062143)
#define Ha (1000000007)

template <typename T> inline bool chkmax(T &a, T b) { return a < b ? a = b, 1 : 0; }
template <typename T> inline bool chkmin(T &a, T b) { return b < a ? a = b, 1 : 0; }

inline int read()
{
register int _, __; register char c_;
for (_ = 0, __ = 1, c_ = getchar(); c_ < '0' || c_ > '9'; c_ = getchar()) if (c_ == '-') __ = -1;
for ( ; c_ >= '0' && c_ <= '9'; c_ = getchar()) _ = (_ << 1) + (_ << 3) + (c_ ^ 48);
return _ * __;
}

inline void File()
{
#ifdef hany01
freopen("bzoj1597.in", "r", stdin);
freopen("bzoj1597.out", "w", stdout);
#endif
}

const int maxn = 50005;

struct Land
{
LL x, y;
inline bool operator < (const Land &A) const {
return x < A.x || (x == A.x && y > A.y);
}
}a[maxn], b[maxn];

LL dp[maxn];
int q[maxn];
int n, j, head, tail, cnt;

inline double slope(int k, int j) { return (dp[j] - dp[k]) * 1.0 / (a[j + 1].y - a[k + 1].y); }

int main()
{
File();

n = read();
For(i, 1, n) b[i].x = read(), b[i].y = read();
sort(b + 1, b + n + 1);
For(i, 1, n) {
while (cnt && b[i].y >= a[cnt].y) -- cnt;
a[++ cnt] = b[i];
}
n = cnt;

q[head = tail = 0] = 0; dp[0] = 0;
For(i, 1, n) {
while (head < tail && slope(q[head], q[head + 1]) >= -a[i].x) ++ head;
j = q[head]; dp[i] = dp[j] + a[i].x * a[j + 1].y; q[++ tail] = i;
while (head + 1 < tail && slope(q[tail - 2], q[tail - 1]) <= slope(q[tail - 1], q[tail]))
q[tail - 1] = q[tail], -- tail;
}

printf("%lld\n", dp
);

return 0;
}
//依旧,依旧,人与绿杨俱瘦。
//    -- 秦观《如梦令·春景》
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: