【HDOJ】1518 Square
DFS+剪枝。与HDOJ 1455如出一辙。
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 5 #define MAXN 25 6 7 int nums[MAXN], n, len, cnt; 8 char visit[MAXN]; 9 10 int comp(const void *a, const void *b) { 11 return *(int *)b - *(int *)a; 12 } 13 14 int dfs(int cnt, int beg, int l) { 15 int i, flg = 0; 16 if (cnt == 3) 17 return 1; 18 if (l == 0) { 19 for (i=0; i<n; ++i) { 20 if ( !visit[i] ) { 21 visit[i] = 1; 22 flg = dfs(cnt+1, i+1, len-nums[i]); 23 visit[i] = 0; 24 break; 25 } 26 } 27 return flg; 28 } 29 30 for (i=beg; i<n; ++i) { 31 if ( !visit[i] ) { 32 if (i && !visit[i-1] && nums[i] == nums[i-1]) 33 continue; 34 if (nums[i] <= l) { 35 visit[i] = 1; 36 flg = dfs(cnt, i+1, l-nums[i]); 37 visit[i] = 0; 38 if (flg) return 1; 39 } 40 } 41 } 42 43 return 0; 44 } 45 46 int main() { 47 int case_n, sum; 48 int i, j; 49 50 scanf("%d", &case_n); 51 52 while (case_n--) { 53 scanf("%d", &n); 54 sum = 0; 55 for (i=0; i<n; ++i) { 56 scanf("%d", &nums[i]); 57 sum += nums[i]; 58 } 59 if ( sum&3 ) 60 printf("no\n"); 61 else { 62 len = sum>>2; 63 qsort(nums, n, sizeof(int), comp); 64 memset(visit, 0, sizeof(visit)); 65 j = 1; 66 for (i=0; i<n; ++i) 67 if (nums[i] > len) { 68 j = 0; 69 break; 70 } 71 if (!j) 72 printf("no\n"); 73 else if ( dfs(0, 0, len) ) 74 printf("yes\n"); 75 else 76 printf("no\n"); 77 } 78 } 79 80 return 0; 81 }