跳到正文

个人记录

solution

afewdgre约 3 分钟
原文
文章信息与版本

文章信息

发布
2026年11月14日
收录
2026年11月14日
更新
2026年11月14日
篇幅
约 3 分钟

版本

  1. v1当前

其实这个题是想让你们知道贪心和 dpdp 也是可以同时结合的。

特殊性质 A 其实提示了你当 K=nK = n 时其实就是按 numnum 排序,然后贪心取。

排序后,我们按顺序决定每个城市”选或不选”。 若一共选了 jj 个城市,当前城市若被选为第 jj 个建造,收益为:

代码
max(0, m_i - (j-1) * num_i)

定义 dpjdp_j 表示已经选了 j 个城市时的最大总收益。 对每个城市 ii(按 numnum 降序处理),从大到小枚举 jj:

代码
dp[j] = max(dp[j], dp[j-1] + max(0, m_i - (j-1) * num_i))

这就是标准的 01 背包:每个城市选或不选,选的话它成为第 jj 个建造的城市。

所以答案为 max_{0 <= j <= K} dp[j]。

复杂度分析

  • 排序:O(nlog⁡n)O(n \log n)
  • DP:O(nK)O(nK)

参考代码

C++
#include<bits/stdc++.h>
using namespace std;
#define int long long 
struct node{
    int m,num;
}a[1005];
bool cmp(node x,node y){
    return x.num>y.num;          // 按 num 降序,损失大的先建
}
int t,n,k,dp[1005]; 
void solve(){
    memset(dp,0,sizeof dp);
    cin>>n>>k;
    for(int i=1;i<=n;i++) cin>>a[i].m;
    for(int i=1;i<=n;i++) cin>>a[i].num;
    sort(a+1,a+1+n,cmp);
    for(int i=1;i<=n;i++){                        // 01 背包:逐个城市考虑
        for(int j=k;j>=1;j--)                     // 倒序枚举已选个数
            dp[j]=max(dp[j],dp[j-1]+max(0ll,a[i].m-(j-1)*a[i].num));
    }
    int maxn=0;
    for(int i=1;i<=n;i++) maxn=max(maxn,dp[i]);   // 取最优(实际 dp[k] 即答案)
    cout<<maxn<<'\n';
}
void afewdgre(){
    cin>>t;
    while(t--) solve(); 
}
signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    afewdgre();
}
原文