标签:
http://acm.hdu.edu.cn/showproblem.php?pid=1455
int dfs(int all,int sum,int now),all代表剩余总长,sum,代表每段长,now代表当前拼接的长度。
if(a[i]+now == sum || now == 0) return 0;
while(a[i+1] == a[i]) i++;
这两句话剪枝很重要。
#include<iostream> #include<string> #include<cstring> #include<algorithm> using namespace std; int a[55],used[55],n; bool cmp(int a,int b) { return a>b; } int dfs(int all,int sum,int now) { if(all == 0 && now == sum) return 1; if(now == sum) now = 0; for(int i = 1;i <= n;i++) { if(used[i] || a[i]+now > sum) continue; used[i] = 1; if(dfs(all-a[i],sum,now+a[i])) return 1; used[i] = 0; if(a[i]+now == sum || now == 0) return 0; while(a[i+1] == a[i]) i++; } return 0; } int main() { while(cin >> n && n) { int sum = 0; for(int i = 1;i <= n;i++) { cin >> a[i]; sum += a[i]; } sort(a+1,a+n+1,cmp); for(int i = a[1];i <= sum;i++) { if(sum%i) continue; memset(used,0,sizeof(used)); if(dfs(sum,i,0)) { cout << i << endl; break; } } } return 0; }
标签:
原文地址:http://www.cnblogs.com/zhurb/p/5873700.html