【DP】 TJU 4074 && CF 319C

斜率优化DP,还是不懂,以后找时间补上好了。。

#include <iostream>
#include <sstream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <bitset>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <climits>
#define maxn 100005
#define eps 1e-6
#define mod 10007
#define INF 99999999
#define lowbit(x) (x&(-x))
//#define lson o<<1, L, mid
//#define rson o<<1 | 1, mid+1, R
typedef long long LL;
using namespace std;

LL a[maxn];
LL b[maxn];
LL dp[maxn];
LL q[maxn];
LL n;

void read(void)
{
	int i;
	for(i = 1; i <= n; i++) scanf("%lld", &a[i]);
	for(i = 1; i <= n; i++) scanf("%lld", &b[i]);
}
void init(void)
{
	memset(q, 0, sizeof q);
	memset(dp, 0, sizeof dp);
}
double g(int aa, int bb)
{
	return (dp[aa] - dp[bb]) / (b[bb] - b[aa]);
}
void work(void)
{
	int h=0, t=0, i;
	dp[1]=0;
	q[++t] = 1;
	for(i = 2; i <= n; i++) {
		while(h+1 < t && g(q[h+1], q[h+2]) < a[i]) ++h;
		dp[i] = dp[q[h+1]] + b[q[h+1]] * a[i];
		while(h+1 < t && g(q[t-1], q[t]) >= g(q[t], i)) --t;
		q[++t] = i;
	}
	printf("%lld\n", dp[n]);
}
int main(void)
{
	while(scanf("%lld", &n)!=EOF) {
		read();
		init();
		work();
	}
	return 0;
}


你可能感兴趣的:(dp)