LS 21 Packing(DP)

本文介绍了一种使用动态规划解决背包问题的方法,通过排序和分组优化,实现最小成本的最大价值分配。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Packing

The cost of set {(a1,b1),(a2,b2),,(an,bn)} is defined as

max{ai}×max{bi}

Partition set {(a1,b1),(a2,b2),,(an,bn)} into several non-empty subsets to minimize the sum of the cost of subsets.

Input

The first line contains an integer n.

n lines follow. Each of them contains two integer ai,bi.

(1n1000,1ai,bi1000)

Ouptut

Single integer denotes the minimum value.

Sample input

3 
1 1
1 3
3 1

Sample output

6

Note

Partition {{(1,1),(1,3)},{(3,1)}} gives the cost of 1×3+3×1=6.

思路:用数组maxn[x][y]表示x到y中最大的b;a就直接排序就行了

          dp[x]表示排序后的前x组的最优值。dp[x]=min(dp[x],maxn[j][i]*a[i]){j<=i}a[i]是排完序以后的。


#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int mm=1010;
const int oo=1e9;
class node
{
  public:int a,b;
}f[mm];
int dp[mm],maxn[mm][mm];
int n;
bool cmp(node a,node b)
{ if(a.a^b.a)
  return a.a<b.a;
  return a.b<b.b;
}
int main()
{
  while(cin>>n)
  {
    for(int i=1;i<=n;i++)
      cin>>f[i].a>>f[i].b;
    sort(f+1,f+n+1,cmp);///以a排序
    memset(maxn,0,sizeof(maxn));
    for(int i=1;i<=n;i++)///找最大的b
    { maxn[i][i]=f[i].b;
      for(int j=i+1;j<=n;j++)
      maxn[i][j]=maxn[i][j-1]>f[j].b?maxn[i][j-1]:f[j].b;
    }
    dp[0]=0;
    for(int i=1;i<=n;i++)
    { dp[i]=oo;int z;
      for(int j=1;j<=i;j++)
      { z=maxn[i-j+1][i]*f[i].a+dp[i-j];
        if(dp[i]>z)dp[i]=z;
      }
    }
    cout<<dp[n]<<"\n";
  }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值