302. 任务安排3

题目链接

302. 任务安排3

\(N\) 个任务排成一个序列在一台机器上等待执行,它们的顺序不得改变。

机器会把这 \(N\) 个任务分成若干批,每一批包含连续的若干个任务。

从时刻 \(0\) 开始,任务被分批加工,执行第 \(i\) 个任务所需的时间是 \(T_i\)

另外,在每批任务开始前,机器需要 \(S\) 的启动时间,故执行一批任务所需的时间是启动时间 \(S\) 加上每个任务所需时间之和。

一个任务执行后,将在机器中稍作等待,直至该批任务全部执行完毕。

也就是说,同一批任务将在同一时刻完成。

每个任务的费用是它的完成时刻乘以一个费用系数 \(C_i\)

请为机器规划一个分组方案,使得总费用最小。

输入格式

第一行包含两个整数 \(N\)\(S\)

接下来 \(N\) 行每行有一对整数,分别为 \(T_i\)\(C_i\),表示第 \(i\) 个任务单独完成所需的时间 \(T_i\) 及其费用系数 \(C_i\)

输出格式

输出一个整数,表示最小总费用。

数据范围

\(1 \le N \le 3 \times 10^5\),
\(0 \le S,C_i \le 512\),
\(-512 \le T_i \le 512\)

输入样例:

5 1
1 3
3 2
4 3
2 3
1 4

输出样例:

153

解题思路

斜率优化dp

本题即 301. 任务安排2 的二分版本,原因在于本题的直线斜率没有单调性

  • 时间复杂度:\(O(nlogn)\)

代码

// Problem: 任务安排3
// Contest: AcWing
// URL: https://www.acwing.com/problem/content/304/
// Memory Limit: 64 MB
// Time Limit: 1000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

// %%%Skyqwq
#include <bits/stdc++.h>
 
//#define int long long
#define help {cin.tie(NULL); cout.tie(NULL);}
#define pb push_back
#define fi first
#define se second
#define mkp make_pair
using namespace std;
 
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
 
template <typename T> bool chkMax(T &x, T y) { return (y > x) ? x = y, 1 : 0; }
template <typename T> bool chkMin(T &x, T y) { return (y < x) ? x = y, 1 : 0; }
 
template <typename T> void inline read(T &x) {
    int f = 1; x = 0; char s = getchar();
    while (s < '0' || s > '9') { if (s == '-') f = -1; s = getchar(); }
    while (s <= '9' && s >= '0') x = x * 10 + (s ^ 48), s = getchar();
    x *= f;
}

const int N=3e5+5;
int n,s,sum[N],w[N];
int hh,tt,q[N];
LL f[N];
int main()
{
    scanf("%d%d",&n,&s);
    for(int i =1;i<=n;i++)
    {
    	scanf("%d%d",&sum[i],&w[i]);
    	sum[i]+=sum[i-1];
    	w[i]+=w[i-1];
    }
    for(int i=1;i<=n;i++)
    {
    	int l=hh,r=tt;
    	while(l<r)
    	{
    		int mid=l+r>>1;
    		if(f[q[mid+1]]-f[q[mid]]>=(LL)(s+sum[i])*(w[q[mid+1]]-w[q[mid]]))r=mid;
    		else
    			l=mid+1;
    	}
    	int j=q[l];
    	f[i]=f[j]-(LL)(s+sum[i])*w[j]+(LL)s*w[n]+(LL)sum[i]*w[i];
    	while(hh<tt&&(__int128)(f[q[tt]]-f[q[tt-1]])*(w[i]-w[q[tt]])>=(__int128)(f[i]-f[q[tt]])*(w[q[tt]]-w[q[tt-1]]))tt--;
    	q[++tt]=i;
    }
    printf("%lld",f[n]);
    return 0;
}
posted @ 2022-12-08 14:56  zyy2001  阅读(28)  评论(0编辑  收藏  举报