题解:AT_abc203_f [ABC203F] Weed

· · 题解

Meaning of the problem

There are n weeds,you can choose no more than k weeds to remove before weeding.

Now given the operation:find the highest weed,we define the height of the highest weed as h and then remove all weeds with a height greater than \frac{h}{2} weeds.

Way of thinking

This is a good dp problem,we need to use dp to solve it.We know dp has four steps in total:state definition,initialization,state transition and answer.

state definition

Use dp_{i,j} to represent the minimum number of weeds that need to be removed in advance when the remaining i th smallest weed has undergone j operations.

initialization

The answer requires finding the minimum value,so we set all values to the maximum and set the number of weeds removed in advance when the operation has not started and all weed is intact to zero.

state transition

We can remove weeds before or during the operation.

Remove this weed before starting the operation:dp_{i-1,j}=\min(dp_{i,j}+1,dp_{i-1,j}).

The subscript of weeds with a height greater than half of the highest weed represented by q needs to be searched using binary search.Remove this weed during operation:dp_{q,j+1}=\min(dp_{q,j+1}+1,dp_{i,j}).

answer

The first dp_{i,0} is less than or equal to k.

Code

#include <bits/stdc++.h>
#define ll long long 
#define Max LONG_LONG_MAX
using namespace std;
const ll N=2e5+5;
ll n,k,a[N],dp[N][35],ans=Max,anss=Max;
void init(){memset(dp,0x3f,sizeof(dp));dp[n][0]=0;}
signed main(){
    cin>>n>>k;
    for(ll i=1;i<=n;i++) cin>>a[i];
    sort(a+1,a+n+1);
    init();
    for(ll i=n;i>=1;i--){
        ll l=1,r=i;while(l<=r){
            ll mid=(l+r)>>1;
            if(a[mid]<=a[i]/2) l=mid+1;
            else r=mid-1;
        }
        ll q=r;for(ll k=0;k<=30;k++){
            dp[i-1][k]=min(dp[i][k]+1,dp[i-1][k]);
            dp[q][k+1]=min(dp[i][k],dp[q][k+1]);
        }
    }for(ll i=0;i<=30;i++){
        if(dp[0][i]<=k){
            ans=i;
            anss=dp[0][i];
            i=31;
        }
    }cout<<ans<<' '<<anss<<endl;

    #define Pyrf_uqcat return 
    #define is 0
    #define lovely ;

    Pyrf_uqcat is lovely

}