Online Judge | Problem Set | Authors | Online Contests | User | ||||||
---|---|---|---|---|---|---|---|---|---|---|
Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest |
谁能帮我看看为什么超时。帮我剪枝一下。#include<stdio.h> #include<iostream> #include<algorithm> using namespace std; bool used[65]; int N,len[65],sum,li,num; int cmp(const void *a,const void *b) { return *(int*)b-*(int*)a; } bool dfs(int level,int l,int rest)/rest:剩余所有的木棒长度 l:当前一根木棒的长度 level:当前的坐标 { if(l==li) return dfs(0,0,rest-li);//当一根木棒填充完毕,rest就减少一根木棒长度 if(!rest) return 1;//当rest为0时,填充完毕。这里我用rest其实和填充木棒的木棒数是一样的。所以这里不可能超时。。 if(level>N-2) return false;//剪枝 int i, temp=0; for(i=level;i<N;i++) { if(!used[i] && l+len[i]<=li && len[i]!=temp)//剪枝 { used[i]=1; if(dfs(i+1,l+len[i],rest)) return 1; used[i]=0; temp=len[i]; if(!i)break; } } return 0; } int main() { int i, flag; while(scanf("%d",&N) && N) { sum=0; for(i=0;i<N;i++) { scanf("%d",&len[i]); sum+=len[i]; } qsort(len,N,sizeof(int),cmp); for(i=N;i>0;i--)//剪枝 { flag=0; if(sum%i!=0 || sum/i<len[0])continue; li=sum/i; memset(used,0,sizeof(used)); if(dfs(0,0,sum)==1){flag = 1;break;} if(flag==1)break; } printf("%d\n",li); } return 0; } Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator