标签:des style blog http color strong
9 5 2 1 5 2 1 5 2 1 4 1 2 3 4 0
6 5
解题:搜索+剪枝。。。NYOJ上这题比POJ 1011要难得多啊,先附上POJ 1011 AC代码 ,待会贴NYOJ 293 AC代码
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cstdlib> 5 #include <vector> 6 #include <climits> 7 #include <algorithm> 8 #include <cmath> 9 #define LL long long 10 using namespace std; 11 int d[70],n,ans,sum; 12 bool vis[70]; 13 bool cmp(const int &a,const int &b) { 14 return b < a; 15 } 16 bool dfs(int cur,int m,int len,int p) { 17 if(m*len == sum-len) return true; 18 if(cur == len) return dfs(0,m+1,len,0); 19 for(int i = p; i < n; i++) { 20 if(!vis[i] && cur+d[i] <= len) { 21 vis[i] = true; 22 if(dfs(cur+d[i],m,len,i+1)) return true; 23 vis[i] = false; 24 if(p == 0) return false; 25 while(i+1 < n && d[i+1] == d[i]) i++; 26 } 27 } 28 return false; 29 } 30 int main() { 31 while(scanf("%d",&n),n) { 32 int i; 33 for(sum = i = 0; i < n; i++) { 34 scanf("%d",d+i); 35 sum += d[i]; 36 } 37 ans = sum; 38 sort(d,d+n,cmp); 39 memset(vis,false,sizeof(vis)); 40 for(i = n; i > 1; i--) 41 if(sum%i == 0 && dfs(0,0,sum/i,0)) {ans = sum/i;break;} 42 printf("%d\n",ans); 43 } 44 return 0; 45 }
NYOJ 293.。。哈..如果当前棍子已经达到预期的长度,却导致后面的无法拼凑出预期的长度,只能怪当前的棍子,所以立即返回。。。因为当前已经满足这个长度了,继续循环,只会导致与当前长度相等或者变短。。。。return 0说明了当前棍子的组合的不合理性
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cstdlib> 5 #include <vector> 6 #include <climits> 7 #include <algorithm> 8 #include <cmath> 9 #define LL long long 10 using namespace std; 11 int d[70],n,ans,sum; 12 bool vis[70]; 13 bool cmp(const int &a,const int &b) { 14 return b < a; 15 } 16 bool dfs(int cur,int m,int len,int p) { 17 if(m*len == sum-len) return true; 18 for(int i = p; i < n; i++) { 19 if(!vis[i] && cur+d[i] <= len){ 20 vis[i] = true; 21 if(cur+d[i] == len){ 22 if(dfs(0,m+1,len,0)) return true; 23 vis[i] = false; 24 return 0;//比POJ上多的优化条件 25 }else{ 26 if(dfs(cur+d[i],m,len,i+1)) return true; 27 vis[i] = false; 28 if(cur == 0) return false; 29 while(i+1 < n && d[i] == d[i+1]) i++; 30 } 31 } 32 } 33 return false; 34 } 35 int main() { 36 while(scanf("%d",&n),n) { 37 int i; 38 memset(d,0,sizeof(d)); 39 for(sum = i = 0; i < n; i++) { 40 scanf("%d",d+i); 41 sum += d[i]; 42 } 43 ans = sum; 44 sort(d,d+n,cmp); 45 memset(vis,false,sizeof(vis)); 46 for(i = n; i > 1; i--){ 47 if(sum%i == 0 && dfs(0,0,sum/i,0)) {ans = sum/i;break;} 48 } 49 printf("%d\n",ans); 50 } 51 return 0; 52 }
NYOJ 293 Sticks,布布扣,bubuko.com
标签:des style blog http color strong
原文地址:http://www.cnblogs.com/crackpotisback/p/3854564.html