HDOJ 4277 USACO ORZ DFS+剪枝

来源:互联网 发布:java 数组长度 编辑:程序博客网 时间:2024/06/05 11:05


                                                                                        USACO ORZ
Time Limit:1500MS    Memory Limit:32768KB     64bit IO Format:%I64d & %I64u


Description




 Like everyone, cows enjoy variety. Their current fancy is new shapes for pastures. The old rectangular shapes are out of favor; new geometries are the favorite.        
I. M. Hei, the lead cow pasture architect, is in charge of creating a triangular pasture surrounded by nice white fence rails. She is supplied with N fence segments and must arrange them into a triangular pasture. Ms. Hei must use all the rails to create three sides of non-zero length. Calculating the number of different kinds of pastures, she can build that enclosed with all fence segments.        
Two pastures look different if at least one side of both pastures has different lengths, and each pasture should not be degeneration.        




                




Input




 The first line is an integer T(T<=15) indicating the number of test cases.        
The first line of each test case contains an integer N. (1 <= N <= 15)        
The next line contains N integers li indicating the length of each fence segment. (1 <= li <= 10000)        




                




Output




 For each test case, output one integer indicating the number of different pastures.        




                




Sample Input




1
3
2 3 4 




                




Sample Output







题意:将n跟木棒分成3堆,3堆木棒的总和分别为a,b,c,满足能以a,b,c组成三角形,问有多少种不同的情况 
 

思路:DFS+剪枝 先固定一根木棒在某一堆(第一根放在a b c 都是等效)所以预处理第一根 

           将木棒由大到小排序 优化时间;

 

#include <cstdio>#include <iostream>#include<algorithm>#include<set>using namespace std;pair<int, int>k;set<pair<int,int>>s;int n,ans,sum;int x[20]; bool cmp(int a, int b){ return a>b;}int find(int a, int b, int c){if (a > b) { int t = a; a = b; b = t; }if (b > c) { int t = b; b = c; c = t; }if (a > b) { int t = a; a = b; b = t; }if (a + b > c){k = make_pair(a, b);if (s.count(k) == 0)    { s.insert(k); return 1;}}return 0;}void DFS(int a, int b ,int c ,int i){   if (a > sum / 2 || b > sum / 2 || c > sum/2 )   return ;if (i == n) { ans += find(a, b,c); }else{DFS(a + x[i + 1], b, c, i + 1);DFS(a, b + x[i + 1], c, i + 1);DFS(a, b,  c + x[i+1] , i + 1);}}int main(){int t;scanf("%d", &t);while (t--){ scanf("%d", &n);sum = 0;for (int i = 1; i <= n; i++){scanf("%d", &x[i]);sum += x[i];}sort(x + 1,x+1+n,cmp);ans = 0;  if(n>=3)  DFS(x[1],0,0,1);printf("%d\n", ans);s.clear();}return 0;}


          
0 0