Solution: Search + pruning... This is much harder than poj 1011 on nyoj. First, attach the poj 1011 AC code and paste the nyoj 293 AC code.
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 long10 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 }
View code
Nyoj 293... Haha. If the current stick has reached the expected length, but the following cannot piece together the expected length, you can only blame the current stick, so return immediately... Because the current length has been satisfied, continuing the loop will only lead to equal or shorter than the current length .... Return 0 illustrates the irrationality of the current combination of sticks.
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 long10 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; // more optimization conditions than those on 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}
View code