CodeForces - 319C Kalila and Dimna in the Logging Industry

Solution

我们令 f [ i ] f[i] f[i] 为砍第 i i i 棵的最小代价。

有转移:

f [ i ] = f [ j ] + a [ i ] × b [ j ] ( 1 ≤ j ≤ i − 1 ) f[i]=f[j]+a[i]\times b[j](1\le j \le i-1) f[i]=f[j]+a[i]×b[j](1ji1)

我们考虑为什么这是对的。(因为实际上我们可以选择先砍后面的再砍前面的)

首先我们证明不存在先砍 k k k,再砍 j j j 的情况(其中 k ≠ n , j < k k\ne n,jk=n,j<k)。因为 b [ n ] = 0 b[n]=0 b[n]=0,所以先砍了 k k k,直接往后砍(因为 b [ k ] < b [ j ] b[k]b[k]<b[j]),等砍到 n n n(即花费为 0 0 0)时再回来一定更优。

所以用斜率优化求出 f [ n ] f[n] f[n] 就行了。

Code

#include 

#define rep(i, _l, _r) for(register signed i = (_l), _end = (_r); i <= _end; ++ i)
#define fep(i, _l, _r) for(register signed i = (_l), _end = (_r); i >= _end; -- i)
#define erep(i, u) for(signed i = head[u], v = to[i]; i; i = nxt[i], v = to[i])
#define print(x, y) write(x), putchar(y)

template <class T> inline T read(const T sample) {
	T x = 0; int f = 1; char s;
	while((s = getchar()) > '9' || s < '0') if(s == '-') f = -1;
	while(s >= '0' && s <= '9') x = (x << 1) + (x << 3) + (s ^ 48), s = getchar();
	return x * f;
}
template <class T> inline void write(const T x) {
	if(x < 0) return (void) (putchar('-'), write(-x));
	if(x > 9) write(x / 10);
	putchar(x % 10 ^ 48);
}
template <class T> inline T Max(const T x, const T y) {return x > y ? x : y;}
template <class T> inline T Min(const T x, const T y) {return x < y ? x : y;}
template <class T> inline T fab(const T x) {return x > 0 ? x : -x;}
template <class T> inline T Gcd(const T x, const T y) {return y ? Gcd(y, x % y) : x;}

typedef long long ll;

const int N = 1e5 + 5;

int n, a[N], b[N], q[N], head = 1, tail;
ll f[N];

double slope(const int j, const int k) {return 1.0 * (f[k] - f[j]) / (b[j] - b[k]);}

int main() {
	n = read(9);
	rep(i, 1, n) a[i] = read(9);
	rep(i, 1, n) b[i] = read(9);
	rep(i, 1, n) {
		while(head < tail && slope(q[head], q[head + 1]) < a[i]) ++ head;
		f[i] = f[q[head]] + 1ll * a[i] * b[q[head]];
		while(head < tail && slope(q[tail], i) < slope(q[tail - 1], q[tail])) -- tail;
		q[++ tail] = i;
	}
	print(f[n], '\n');
	return 0;
}

你可能感兴趣的:(#,斜率优化)