P4799 世界冰球锦标赛 ( 折半查找

#include 
using namespace std;
using VI = vector;
using PII = pair;
using ll = long long;
using ull = unsigned long long;
ll n;
ll m;
ll a[60];
vector d1;
ll res = 0;
void dfs(int now,ll money,int limit){
    if(now > limit){
        d1.push_back(money);
        return;
    }
    if(a[now] + money <= m){
        dfs(now+1,a[now] + money,limit);
    }
    dfs(now+1,money,limit);
}
bool cmp(ll a,ll b){
    return a > b;
}

void dfs2(int now,ll money,int limit){
    if(now > limit){
        int left = 0,right = d1.size()-1;
        while(left < right){
            int mid = (left + right + 1) >> 1;
            if(money + d1[mid] <= m){
                left = mid;
            }else{
                right = mid - 1;
            }
        }
        res += left + 1;
        return;
    }

    if(a[now] + money <= m){
        dfs2(now+1,a[now] + money,limit);
    }
    dfs2(now+1,money,limit);


}
int main(){
    cin>>n>>m;
    for(int i=1;i<=n;i++) cin>>a[i];
    sort(a+1,a+1+n,cmp);
    dfs(1,0,n/2);
    sort(d1.begin(),d1.end());
    dfs2(n/2+1,0,n);
    cout<

水绿题

注意开long long 

你可能感兴趣的:(搜索,深度优先,算法)