usaco4.1.2

usaco4.1.2

太忙没时间啰嗦,二分+dfs
要注意木板有很多大小相同的!!!

其它的自己看看
代码
/*
USER:zyn19961
TASK:fence8
LANG:C++
*/
#include
<cstdio>
#include
<cstring>
    
bool can(int x);
    
bool dfs(int now,int lp,int x);
    
void sort(int x[],int s,int t);
    
int n,a[51],p[51],r;
    
int b[1025],sum[1025];
    
int ans,tot,waste;
    
int main(){
        
int s,t,m;
        freopen(
"fence8.in","r",stdin);
        freopen(
"fence8.out","w",stdout);
        scanf(
"%d",&n);
        
for(int i=1;i<=n;i++){
            scanf(
"%d",&a[i]);
            tot
+=a[i];
            }
        scanf(
"%d",&r);
        sum[
0]=0;
        
for(int i=1;i<=r;i++)
            scanf(
"%d",&b[i]);
        sort(a,
1,n);
        sort(b,
1,r);
        
for(int i=1;i<=r;i++)
            sum[i]
=sum[i-1]+b[i];
        s
=1;t=r;ans=0;
        
while(s<=t){
            m
=(s+t+1)/2;
            
if(can(m)){
                ans
=m;
                s
=m+1
                }
            
else
                t
=m-1
            }
        printf(
"%d\n",ans);
        fclose(stdin);
        fclose(stdout);
        
return 0;
        } 
    
void sort(int x[],int s,int t){
        
for(int i=s;i<=t;i++)
            
for(int j=i+1;j<=t;j++)
                
if(x[i]>x[j]){
                    x[i]
^=x[j];
                    x[j]
^=x[i];
                    x[i]
^=x[j];
                    }
        }
    
bool can(int x){
        waste
=0;
        
for(int i=1;i<=n;i++)
            p[i]
=a[i];
        
if(dfs(x,0,x))return true;
        
else return false
        } 
    
bool dfs(int now,int lp,int x){//
        int i,j;
        
bool change;
        
if(now==0)return true;
        
if(waste+sum[x]>tot)return false;
        
if(now!=x&&b[now]==b[now+1])j=lp;else j=1;//very important
        for(int i=j;i<=n;i++)
            
if(p[i]>=b[now]){
                p[i]
-=b[now];
                change
=false;
                
if(p[i]<b[1]){//attention
                    change=true;
                    waste
+=p[i];
                    }
                
if(dfs(now-1,i,x))return true;
                
if(change)waste-=p[i];
                p[i]
+=b[now];
                }
        
return false;
        } 



你可能感兴趣的:(usaco4.1.2)