POJ1011-Sticks
http://poj.org/problem?id=1011
#include<iostream> #include<cstring> #include<algorithm> using namespace std; int p[65],vis[65],s,j,n; bool cmp(int a,int b) { return a>b; } int dfs(int sum,int k,int cnt) { if(cnt==s) return 1; else if(sum==j) return dfs(0,0,cnt+1); else { int pre,i; for(pre=0,i=k;i<n;i++) if(vis[i]&&p[i]!=pre&&p[i]+sum<=j) { pre=p[i]; vis[i]=0; if(dfs(sum+p[i],i+1,cnt)) break; vis[i]=1; if(k==0) return 0; } if(i==n) return 0; else return 1; } } int main(void) { int i,sum; while(cin>>n,n) { for(i=sum=0;i<n;i++) { cin>>p[i]; sum+=p[i]; } sort(p,p+n,cmp); for(j=p[0];j<sum;j++) if(sum%j==0) { s=sum/j; memset(vis,1,sizeof(vis)); if(dfs(0,0,0)) break; } if(j==sum) cout<<sum<<endl; else cout<<j<<endl; } return 0; }