給定木棍序列,求解能將木棍拼成相同長度的數根長木棍的狀況下長木棍長度的最小值。ios
/*hdu1455dfs */ #include<bits/stdc++.h> using namespace std; typedef unsigned int ui; typedef long long ll; typedef unsigned long long ull; #define pf printf #define prime1 1e9+7 #define prime2 1e9+9 #define scand(x) scanf("%llf",&x) #define f(i,a,b) for(int i=a;i<=b;i++) #define scan(a) scanf("%d",&a) #define dbg(args) cout<<#args<<":"<<args<<endl; #define pb(i) push_back(i) #define ppb(x) pop_back(x) #define maxn 100 int a[maxn],used[maxn],n; int tot,ans,target; int flag; void dfs(int now,int finish,int pos) { if(flag)return; if(finish==tot/target) { flag=1; return; } // if(num+a[n]>target)return;//最短的一根木棍和當前木棍沒法拼成,則搜索失敗 f(i,pos,n) { if(used[i])continue; if(a[i]+now>target)continue; used[i]=true; if(now+a[i]==target) { dfs(0,finish+1,1); } else { dfs(now+a[i],finish,i+1); } if(flag)return; used[i]=false; if(!now)return;//數根已經能夠拼成target長度,可是剩餘木棍中較長的一根做爲首選沒法達成要求,說明第一根會被廢棄 while(a[i]==a[i+1]&&i+1<=n)i++;//前面用相同長度的木棍,沒法拼成,則後面用一樣長度的也不能拼成 } } int main() { std::ios::sync_with_stdio(false); while(scan(n)==1&&n) { flag=0; tot=0; ans=0; f(i,1,n) { scan(a[i]); tot+=a[i]; } sort(a+1,a+n+1,greater<int>());//降序 ,老是現用最長的木棍最爲第一根檢查是否能夠拼接 f(i,a[1],tot) //實際上最長不可能超過tot/2, { if(tot%i==0) { memset(used,0,sizeof(used)); target=i; dfs(0,0,1); if(flag) { ans=target; break; } } } if(!flag)pf("%d\n",tot); else pf("%d\n",ans); } }