链接:点击打开链接
题意:给出n个矩阵,要求挖至少m个洞,每个洞的代价为洞的面积,使得全部矩形能够通过,代价最小为多少
代码:
#include <math.h>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
struct node{
long long w,h;
friend bool operator<(node a,node b){
if(a.h==b.h)
return a.w<b.w;
return a.h>b.h;
}
}s[50005];
long long q[50005],dp[105][50005];
long long getx(long long x){
return -1*s[x+1].h;
}
long long gety(long long x,long long y){
return dp[x][y];
}
long long cross(long long x1,long long y1,long long x2,long long y2,long long x3,long long y3){
return (y3-y1)*(x2-x1)-(y2-y1)*(x3-x1);
}
int main(){
long long i,j,k,n,m,ans,cnt,head,tail;
while(scanf("%lld%lld",&n,&m)!=EOF){
for(i=1;i<=n;i++)
scanf("%lld%lld",&s[i].w,&s[i].h);
sort(s+1,s+n+1);
cnt=1;
for(i=2;i<=n;i++){
if(s[cnt].w<s[i].w)
s[++cnt]=s[i]; //将矩阵按h递减,w递增排序
} //去掉被包含的矩阵
n=cnt;
m=min(m,n);
memset(dp,0,sizeof(dp));
for(i=1;i<=n;i++)
dp[1][i]=s[1].h*s[i].w;
for(i=2;i<=m;i++){ //dp[i][j]表示到第j个矩阵,挖了i个洞的费用
head=tail=0; //dp[i][j]=min(dp[i-1][k]+h[k+1]*w[j])
for(j=1;j<=n;j++){ //k=s[j].w,所以斜率递增,维护一个斜率递增的凸包
k=s[j].w;
while((head+1<tail)&&cross(getx(q[tail-2]),gety(i-1,q[tail-2]),getx(q[tail-1]),gety(i-1,q[tail-1]),getx(j),gety(i-1,j))<=0)
tail--;
q[tail++]=j;
while((head+1<tail)&&((gety(i-1,q[head+1])-gety(i-1,q[head]))<=k*(getx(q[head+1])-getx(q[head]))))
head++; //求切点
dp[i][j]=gety(i-1,q[head])-k*getx(q[head]);
}
}
ans=dp[1][n];
for(i=1;i<=m;i++)
ans=min(ans,dp[i][n]);
printf("%lld\n",ans);
}
return 0;
}