智码测试题解

· · 题解

A

树剖模板改一改就好了,具体不作赘述。

B

解题思路

  1. 将物品按花费从小到大排序。
  2. 预处理 su[i][t]:第 i \sim n 件物品中选取价值最大的 t 件的总价值。
  3. 0‑1背包:从前 i 件中花钱选出若干件;每当得到合法付费状态,计算付费件数对应的免费名额,免费物品只能取自尚未进入背包的 i+1\sim n,查表累加免费价值,更新全局答案。
  4. 对答案数组做后缀最大值,输出预算 1\sim m 的答案。

核心技巧:免费部分价值不存入DP状态,转移时现场查表,省去一维状态。

DP状态

变量含义

变量 含义
e[i].st 物品 i 的购买花费
e[i].ed 物品 i 的价值
su[i][t] 物品 i\sim n 中价值最大 t 件的价值总和
j 花钱购买的物品件数
k 总花费 / 预算
\left\lfloor \dfrac{j}{a}\right\rfloor+\left\lfloor \dfrac{j}{b}\right\rfloor 购买 j 件解锁的免费名额
free=\min(n-i,\left\lfloor \dfrac{j}{a}\right\rfloor+\left\lfloor \dfrac{j}{b}\right\rfloor) 实际可取免费件数;免费候选池:i+1\sim n

状态转移

f[j][k]=\max\big(f[j][k],\ f[j-1][k-e[i].st]+e[i].ed\big) dp[k]=\max\big(dp[k],\ f[j][k]+su[i+1][free]\big)

输出预处理

dp[i]=\max(dp[i],dp[i-1])

预算越高答案不会变差,做后缀取最大值。

C

D

思路

  1. 输入物品,a_{i_{st}} \to 开始时间,a_{i_{ed}} \to 结束时间
  2. 以 ed 为第一关键字 从小到大排序,以st为第二关键字从小到大排序。
  3. 定义变量:nw \to \texttt{\small 当前下标} , ans ,t \to \texttt{\small 当前时间} , p \to \texttt{\small当前时间已经使用 p 个物品}
  4. 循环遍历。
    • 若当前时间 t < a_{nw} .st ,则所有物品无法使用,令 t=a_{nw} .st
    • 如 a_{nw} .st < t < a_{nw} .ed, 那么ans \texttt{\small{不变}},p++ 表示当前 t 时间使用 p 个物品。
    • 如 a_{nw} .ed<t,已超时 ans=\max((t-a_{nw}.ed),ans)
  5. 如果当前 nw ,已使用 nw\to nw+1
  6. 如果p \ge m,意味着当前时间的最大可使用物品数量已达到,则 p=0,t \to t+1 ,表示 p 清空,时间移动至下一位。
  7. 输出答案即可

    代码

    ::::success[AC code]

    #include<bits/stdc++.h>
    using namespace std;
    #define int long long
    const int mx=1e6+5;
    int n,m,nw,ans;
    struct node{
     int st,ed;
    }a[mx];
    bool cmp(node a,node b){
     if(a.ed==b.ed)return a.st<b.st;
     return a.ed<b.ed;
    }
    signed main(){
     ios::sync_with_stdio(0);
     cin.tie(0),cout.tie(0);
     cin>>n>>m;
     for(int i=1;i<=n;i++)cin>>a[i].st>>a[i].ed;
     sort(a+1,a+n+1,cmp);
     int t=0,p=0,nw=1;
     while(nw<=n){
         if(t<a[nw].st)t=a[nw].st;
         ans=max((t-a[nw].ed),ans);
         p++;
         if(p==m)t++,p=0;
         nw++;
     }
     cout<<ans;
     return 0;
    }

    ::::

    复杂度正确性

证明1:注意到 t < a_{nw} .ed ,t =a_{nw}.ed, \therefore t最多改变 2\times n 次 ,复杂度 O(n)

证明2:注意到解法中每次nw++,因为 nw \le n, 所以\texttt {while} 循环至多执行 n 次。