我自己优化搜索,从20分改到了80分,不知道还能怎么优化了
#include<bits/stdc++.h>
#define ll unsigned int
using namespace std;
ll n,m;
ll a[35],c[105],ans=1e8,t[105],cnt,l,r,mid,sum,minn,pot=1;
bool cmp(ll l,ll r){
return l>r;
}
struct node{
ll x,id;
}b[25000005];
bool Cmp(node l,node r){
return l.x<r.x;
}
void dfs(ll x,ll p){
if(p>=(1<<n)-1){
ans=min(x,ans);
return;
}
if(x>=ans) return;
if(x>m) return;
l=1,r=cnt;
ll t=-1;
while(l<=r){
mid=(l+r)>>1;
if(b[mid].x<=c[x]) l=mid+1,t=mid;
else r=mid-1;
}
for(ll i=t;i>=1;i--){
ll block=pot,spr=p|b[i].id;
while((spr&(1<<(pot-1)))&&pot<=n) pot++;
if(a[pot]+b[i].x<=c[x]&&pot<=n) {pot=block;continue;}
if((b[i].id&p)) {pot=block;continue;}
dfs(x+1,spr);
pot=block;
}
}
inline int read(){
ll x = 0, f = 1;
char ch = getchar();
while (!isdigit(ch)){
if (ch == '-')
f = -1;
ch = getchar();
}
while (isdigit(ch)){
x = (x << 1) + (x << 3) + (ch ^ 48);
ch = getchar();
}
return x * f;
}
inline void write(ll x){
if (x < 0) putchar('-'), x = -x;
if (x > 9) write(x / 10);
putchar(x % 10 + '0');
}
int main(){
n=read(),m=read();
for(int i=1;i<=n;i++) a[i]=read();
for(int i=1;i<=m;i++) c[i]=read();
sort(a+1,a+n+1),pot=1,a[n+1]=1e7;
for(int i=0;i<(1<<n);i++){
sum=0;
for(int j=1;j<=n;j++){
if((i>>(j-1))&1) sum+=a[j];
}
b[++cnt].x=sum,b[cnt].id=i;
}
sort(b+1,b+cnt+1,Cmp);
sort(c+1,c+m+1,cmp);
dfs(1,0);
if(ans==1e8) printf("NIE");
else write(ans-1);
system("pause");
exit(0);
return 0;
}