# 【BZOJ5311】【CF321E】贞鱼/Ciel and Gondolas（DP，凸优化）

## Description

n只贞鱼到陆地上乘车，现在有k辆汽车可以租用。

## Code

BZOJ卡常哇，加了个fread就卡过去了2333

/**************************************
* Au: Hany01
* Prob: [BZOJ5311][CF321E] 贞鱼
* Date: Aug 11th, 2018
* Email: hany01@foxmail.com
**************************************/

#include<bits/stdc++.h>

using namespace std;

typedef long long LL;
typedef pair<int, int> PII;
typedef vector<int> VI;
#define File(a) freopen(a".in", "r", stdin), freopen(a".out", "w", stdout)
#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 SZ(a) ((int)(a.size()))
#define ALL(a) a.begin(), a.end()
#define pb(a) push_back(a)
#define mp(a, b) make_pair(a, b)
#define x first
#define y second
#define INF (0x3f3f3f3f)
#define INF1 (2139062143)
#define y1 wozenmezhemecaia
#ifdef hany01
#define debug(...) fprintf(stderr, __VA_ARGS__)
#else
#define debug(...)
#endif

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 char getChar(){
static char buf[100000], *p1=buf, *p2=buf;
return p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 100000, stdin), p1 == p2) ? EOF : *p1 ++;
}
register char ch=getChar(); register int sum=0;
while (!(ch >= '0' && ch <= '9')) ch = getChar();
while(ch >= '0' && ch <= '9') sum = sum * 10 + ch - 48, ch = getChar();
return sum;
}

const int maxn = 4005;

static PII f[maxn];
static int w[maxn][maxn], n;

inline int calc(int i, int j) { return w[i][i] - w[j][i] - w[i][j] + w[j][j] + f[j].x; }

inline void check(int dt) {
static PII stk[maxn];
register int top, pos, bot;
stk[top = bot = 1] = mp(0, 0);

For(i, 1, n) {
if (bot < top && stk[bot + 1].x <= i) ++ bot;
f[i].x = calc(i, pos = stk[bot].y) + dt;
f[i].y = f[pos].y + 1;
if (calc(n, i) < calc(n, stk[top].y)) {
stk[++ top] = mp(n, i);
for (register int l, r, mid; ; ) {
l = max(stk[top - 1].x, i + 1), r = n;
while (l < r) {
mid = (l + r) >> 1;
if (calc(mid, stk[top - 1].y) > calc(mid, i)) r = mid; else l = mid + 1;
}
stk[top].x = l;
if (stk[top].x > stk[top - 1].x) break;
stk[top - 1] = stk[top], -- top;
}
}
}
}

int main()
{
#ifdef hany01
File("bzoj5311");
#endif

static int l, r, mid, k;

For(i, 1, n) For(j, 1, n)
w[i][j] = w[i - 1][j] + w[i][j - 1] - w[i - 1][j - 1] + (i <= j ? read() : (read(), 0));

l = 0, r = w[n][n];
while (l < r) {
mid = (l + r) >> 1, check(mid);
if (f[n].y <= k) r = mid; else l = mid + 1;
}
check(l);
printf("%d\n", f[n].x - l * k);

return 0;
}