P2365 任务安排 斜率优化入门

zz:https://www.cnblogs.com/ttttttttrx/p/12650507.html

//O(N*N)
#include<bits/stdc++.h>
using namespace std;
#define pb push_back
#define F first
#define S second
#define mkp make_pair
#define pii pair<int,int>
typedef long long ll;
const int inf=0x3f3f3f3f;
const int maxn=1e6+10;
const int mod=1e9+7;
int dp[maxn],sumt[maxn],sumf[maxn];
int main(){
	int n,s;
	scanf("%d%d",&n,&s);
	for(int i=1;i<=n;i++){
		int x,y;scanf("%d%d",&x,&y);
		sumt[i]=sumt[i-1]+x;
		sumf[i]=sumf[i-1]+y;
	}
	for(int i=1;i<=n;i++)dp[i]=inf;
	dp[0]=0;
	for(int i=1;i<=n;i++){
		for(int j=1;j<=i;j++){
			dp[i]=min(dp[i],dp[j-1]+sumt[i]*(sumf[i]-sumf[j-1])+s*(sumf[n]-sumf[j-1]));
		}
	}
	cout<<dp[n];
	return 0;
}

  斜率优化

#include<bits/stdc++.h>
using namespace std;
#define pb push_back
#define F first
#define S second
#define mkp make_pair
#define pii pair<int,int>
typedef long long ll;
const int inf=0x3f3f3f3f;
const int maxn=1e6+10;
const int mod=1e9+7;
int dp[maxn],sumt[maxn],sumf[maxn],q[maxn];
int main(){
	int n,s;
	scanf("%d%d",&n,&s);
	for(int i=1;i<=n;i++){
		int x,y;scanf("%d%d",&x,&y);
		sumt[i]=sumt[i-1]+x;
		sumf[i]=sumf[i-1]+y;
	}
	for(int i=1;i<=n;i++)dp[i]=inf;
	dp[0]=0;
	int l,r=1;
	r=l=1;
	for(int i=1;i<=n;i++){
		while(l<r&&(dp[q[l+1]]-dp[q[l]])<=(s+sumt[i])*(sumf[q[l+1]]-sumf[q[l]]))l++;
		dp[i]=dp[q[l]]+sumt[i]*(sumf[i]-sumf[q[l]])+s*(sumf[n]-sumf[q[l]]);
		while(l<r&&(dp[q[r]]-dp[q[r-1]])*(sumf[i]-sumf[q[r]])>=(dp[i]-dp[q[r]])*(sumf[q[r]]-sumf[q[r-1]]))r--;
		q[++r]=i;
	}
	cout<<dp[n];
	return 0;
}

  https://www.cnblogs.com/terribleterrible/p/9669614.html

posted @ 2020-09-28 18:08  我微笑不代表我快乐  阅读(254)  评论(0编辑  收藏  举报