题意:现有M根木棒,要裁成N根,问最多几根能裁。
范围:M<=50,N<=1000,长度保证不暴int;
解法:排序后二分答案,一开始验证打算用DP,后来发现不可行,再想搜索,T了无数发,最后发现大视野不需要用EOF……躺跪orz,剪枝参考博客里的 POJ1011,再加上了一个浪费剪枝。
代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
#include<iostream>
#include<stdlib.h>
#include<set>
#include<map>
#include<queue>
#include<vector>
#include<bitset>
#pragma comment(linker, "/STACK:1024000000,1024000000")
template <class T>
bool scanff(T &ret){ //Faster Input
char c; int sgn; T bit=0.1;
if(c=getchar(),c==EOF) return 0;
while(c!='-'&&c!='.'&&(c<'0'||c>'9')) c=getchar();
sgn=(c=='-')?-1:1;
ret=(c=='-')?0:(c-'0');
while(c=getchar(),c>='0'&&c<='9') ret=ret*10+(c-'0');
if(c==' '||c=='\n'){ ret*=sgn; return 1; }
while(c=getchar(),c>='0'&&c<='9') ret+=(c-'0')*bit,bit/=10;
ret*=sgn;
return 1;
}
#define inf 1073741823
#define llinf 4611686018427387903LL
#define PI acos(-1.0)
#define lth (th<<1)
#define rth (th<<1|1)
#define rep(i,a,b) for(int i=int(a);i<=int(b);i++)
#define drep(i,a,b) for(int i=int(a);i>=int(b);i--)
#define gson(i,root) for(int i=ptx[root];~i;i=ed[i].next)
#define tdata int testnum;scanff(testnum);for(int cas=1;cas<=testnum;cas++)
#define mem(x,val) memset(x,val,sizeof(x))
#define mkp(a,b) make_pair(a,b)
#define findx(x) lower_bound(b+1,b+1+bn,x)-b
#define pb(x) push_back(x)
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
int a[1111],b[1111];
int an,bn,tota,totb;
int dbn,m;
bool vis[1111];
int last;
bool dfs(int x,int rest,int waste,int num){
if(num==m)return true;
if(tota-totb<waste||x>an)return false; //如果浪费太多,直接返回false
int pd=0;
rep(i,(rest==a[x])?1:last+1,m){ //不需要从头枚举,因为之前的枚举过了
if(i>1&&b[i]==b[i-1]&&!vis[i-1])continue; //如果这个长度之前的false了,直接跳过
if(!vis[i]&&b[i]<=rest){
vis[i]=1;
last=i;
if(dfs(x,rest-b[i],waste,num+1))return true;//如果成功了当然直接true啦
vis[i]=0;
pd=1;
}
}
if(!pd&&dfs(x+1,a[x+1],waste+rest,num))return true;//这个木棒不能再拼了,放弃这个木棒,选择下一根,浪费的累加
return false;
}
int sum[1111];
bool pdf(int x){
m=x;
totb=sum[x];
rep(i,1,x)vis[i]=0;
return dfs(1,a[1],0,0);
}
int dp[1111];
int main(){
scanff(an);
tota=0;
rep(i,1,an)scanff(a[i]),tota+=a[i];
sort(a+1,a+1+an);
scanff(bn);
rep(i,1,bn)scanff(b[i]);
sum[0]=0;
sort(b+1,b+1+bn);
rep(i,1,bn)sum[i]=sum[i-1]+b[i];
int l=0,r=bn;
mem(dp,-1);
while(l+1<r){
int mid=(l+r)>>1;
if(dp[mid]==-1){
dp[mid]=pdf(mid);
}
if(dp[mid])l=mid;
else r=mid;
}
if(dp[r]==-1)dp[r]=pdf(r);
if(dp[r])printf("%d\n",r);
else printf("%d\n",l);
}
/*
20
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
100
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
*/