【uva307】小木棍 Sticks [dfs搜索]

我枯辽

开始这一段

if(cnt==m) return 1;
if(l==len) return dfs(cnt+1,0,1);

打成了

if(cnt==m) return 1;
if(l==len) dfs(cnt+1,0,1);

然后导致一直爆炸

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 const int N=100+5; 
 4 bool v[N];
 5 int len,n,a[N],sum,m;
 6 template<class t>void rd(t &x)
 7 {
 8     x=0;int w=0;char ch=0;
 9     while(!isdigit(ch)) w|=ch=='-',ch=getchar();
10     while(isdigit(ch)) x=(x<<1)+(x<<3)+(ch^48),ch=getchar();
11     x=w?-x:x;
12 }
13 bool cmp(int a,int b) {return a>b;}
14 
15 bool dfs(int cnt,int l,int last)
16 {
17     if(cnt==m) return 1;
18     if(l==len) return dfs(cnt+1,0,1);
19     int fail=0;
20     for(int i=last;i<=n;i++)
21     {
22         if(v[i]==0&&a[i]+l<=len&&fail!=a[i])
23         {
24             v[i]=1;
25             if(dfs(cnt,l+a[i],i)) return 1;
26             v[i]=0;fail=a[i];//回溯 当前长度失败了 
27             if(l==0||l+a[i]==len) return 0;
28         }
29     }
30     return 0;
31 }
32 
33 int main()
34 {
35     while(scanf("%d",&n)&&n)
36     {
37         sum=0;
38         for(int i=1;i<=n;i++) {rd(a[i]);sum+=a[i];}
39         sort(a+1,a+n+1,cmp);//排序 
40         for(len=a[1];len<=(sum>>1);len++)
41         {
42              if(sum%len) continue;
43              m=sum/len;
44              memset(v,0,sizeof(v));
45              if(dfs(1,0,1)) {printf("%d\n",len); break;}
46         }
47         if(len>sum>>1) printf("%d\n",sum);
48     }
49         return 0;
50 }
100昏

猜你喜欢

转载自www.cnblogs.com/lxyyyy/p/10495015.html