USACO ORZ
Time Limit: 5000/1500 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 4954 Accepted Submission(s): 1630
Problem 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.
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)
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
1
//思路:用dfs搜索,然后用set判重(注意代码中的技巧,保证x y z是从小到大排序,且x*1000000+y再放到set中,不能直接x+y放到set中,这样6 6 9和4 8 9就不能正确判断)
AC源码:
#include <iostream>
#include <set>
using namespace std;
typedef long long LL;
LL sum,A[25],n;
set<LL> s;
void dfs(int cnt,int x,int y)
{
LL z=sum-x-y;
if(cnt==n)
{
if(x<=y&&y<=z&&x+y>z)
{
//调试语句 cout<<"x:"<<x<<" y:"<<y<<" z:"<<z<<endl;
s.insert(x*1000000+y);
}
return ;
}
dfs(cnt+1,x+A[cnt],y);
dfs(cnt+1,x,y+A[cnt]);
dfs(cnt+1,x,y);
}
int main()
{
int T;
cin>>T;
while(T--)
{
s.clear();
sum=0;
cin>>n;
for(int i=0;i<n;++i)
{
cin>>A[i];
sum+=A[i];
}
dfs(0,0,0);
cout<<s.size()<<endl;
}
return 0;
}