做题感悟:这题主要是处理一下前缀和,跟 01 背包用搜索解的处理差不多。
解题思路:
1. 从当前值开始,如果选上剩下的所有(前缀和处理),也不能小于已得最优值的话,返回。
2. 最优值不用等到累积选到k数才更新,而是不断更新,因为与运算结果比原来两个都小,所以这也是一个剪枝。
3. 预处理,从小到大排序,可想而知,先选小的,得到的最优值更接近于结果,是个强剪枝,没有这个2900ms+,加上600ms+。
代码:
#include<stdio.h> #include<iostream> #include<map> #include<stack> #include<string> #include<string.h> #include<stdlib.h> #include<math.h> #include<vector> #include<queue> #include<algorithm> using namespace std ; #define lld __int64 const double PI = 3.1415926 ; const double esp = 1e-4 ; const int md= 2810778 ; const lld INF = 0x7fffffffffffffff ;// 这一定要注意 const lld MX = 45 ; lld n,m,ans ; lld g[MX],sum[MX] ; void dfs(lld x,lld num,lld cnt) { if(ans>cnt) ans=cnt ;// 每次更新 if(x==n||num==m) return ; lld sx=cnt&sum[x] ; if(sx>=ans) return ; dfs(x+1,num+1,cnt&g[x]) ; // 选入 x 元素 dfs(x+1,num,cnt) ;// 抛弃 } int main() { lld Tx,q=1 ; scanf("%I64d",&Tx) ; while(Tx--) { scanf("%I64d%I64d",&n,&m) ; for(int i=0 ;i<n ;i++) scanf("%I64d",&g[i]) ; sort(g,g+n) ; sum[n-1]=g[n-1] ; for(lld j=n-2 ;j>=0 ;j--) // 前缀和 sum[j]=g[j]&sum[j+1] ; ans=INF ; dfs(0,0,ans) ; printf("Case #%I64d: %I64d\n",q++,ans) ; } return 0 ; }