Description
A team of k (1 <= K <= 100) workers should paint a fence which contains N (1 <= N <= 16 000) planks numbered from 1 to N from left to right. Each worker i (1 <= i <= K) should sit in front of the plank Si and he may paint only a compact interval (this means that the planks from the interval should be consecutive). This interval should contain the Si plank. Also a worker should not paint more than Li planks and for each painted plank he should receive Pi $ (1 <= Pi <= 10 000). A plank should be painted by no more than one worker. All the numbers Si should be distinct.
Being the team’s leader you want to determine for each worker the interval that he should paint, knowing that the total income should be maximal. The total income represents the sum of the workers personal income.
Write a program that determines the total maximal income obtained by the K workers.
题目分析
题意:有n块木板,m个工匠,第i个工匠要么不粉刷,要么粉刷包含木板Si的、长度不超过Li的连续的一段木板,每粉刷一块可以得到Pi的报酬,每块木板至多被粉刷一次,求工匠们能获得的最大总报酬
首先将工人按Si升序排序
设dp[i][j]表示前 i 个工人粉刷前 j 块木板能获得的最大总报酬
转移分为三种
d
p
[
i
]
[
j
]
=
d
p
[
i
−
1
]
[
j
]
dp[i][j]=dp[i-1][j]
dp[i][j]=dp[i−1][j],即第i个工人不参与粉刷
d
p
[
i
]
[
j
]
=
d
p
[
i
]
[
j
−
1
]
dp[i][j]=dp[i][j-1]
dp[i][j]=dp[i][j−1],第i个工人粉刷的区域不包含j
d
p
[
i
]
[
j
]
=
m
a
x
(
d
p
[
i
−
1
]
[
k
]
+
(
j
−
k
)
P
i
)
,
(
j
−
L
i
≤
k
<
j
且
k
<
S
i
)
dp[i][j]=max(dp[i-1][k]+(j-k)P_i),\ (j-L_i\leq k< j且k<S_i)
dp[i][j]=max(dp[i−1][k]+(j−k)Pi), (j−Li≤k<j且k<Si),即第i个工人粉刷的区域为k+1到j
其中仅当
S
i
≤
j
≤
S
i
+
L
i
−
1
S_i\leq j\leq S_i+L_i-1
Si≤j≤Si+Li−1时需要第三种转移
第三种转移是求每段长为Li的区间中的最大值,显然可以单调队列维护
而Si升序排序则保证在转移中不会出现一块木板被粉刷多次
#include<iostream>
#include<vector>
#include<algorithm>
#include<queue>
#include<cstring>
#include<cstdio>
using namespace std;
int read()
{
int f=1,x=0;
char ss=getchar();
while(ss<'0'||ss>'9'){if(ss=='-')f=-1;ss=getchar();}
while(ss>='0'&&ss<='9'){x=x*10+ss-'0';ss=getchar();}
return f*x;
}
const int maxn=50010;
int n,m;
struct Worker{int L,P,S;}wrk[maxn];
int dp[110][maxn];
int q[maxn];
bool cmp(Worker a,Worker b){
return a.S<b.S;
}
int calc(int i,int pos){
return dp[i-1][pos]-pos*wrk[i].P;
}
int main()
{
n=read(); m=read();
for(int i=1;i<=m;++i)
{
wrk[i].L=read();
wrk[i].P=read();
wrk[i].S=read();
}
sort(wrk+1,wrk+1+m,cmp);
for(int i=1;i<=m;++i)
{
int Si=wrk[i].S, Li=wrk[i].L, Pi=wrk[i].P;
int ll=1,rr=1;
q[rr++]=0; // 来自dp[i-1][0]的转移
for(int j=1;j<=n;++j)
{
dp[i][j]=max(dp[i][j],max(dp[i-1][j],dp[i][j-1]));
while(ll<rr&&q[ll]<j-Li) ++ll;
if(j>=Si&&j<=Si+Li-1){
if(ll<rr) dp[i][j]=max(dp[i][j],calc(i,q[ll])+j*Pi);
}
if(j<Si) // 转移的位置必须小于Si
{
while(ll<rr&&calc(i,q[rr-1])<=calc(i,j)) --rr;
q[rr++]=j;
}
}
}
printf("%d",dp[m][n]);
return 0;
}