HDOJ4277USACO ORZ【dfs+剪枝】

来源:互联网 发布:linux安装xz软件 编辑:程序博客网 时间:2024/05/24 06:21

USACO ORZ

Time Limit: 5000/1500 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4333    Accepted Submission(s): 1430


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.
 

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
132 3 4
 

Sample Output
1
 

Source
2012 ACM/ICPC Asia Regional Changchun Online
 

#include<bits\stdc++.h>using namespace std;const int maxn=10010;int num[maxn];int temp[5];int ans,sum,n;map<long long ,int>vis;bool judge(int a,int b,int c){return a+b>c;}void dfs(int a,int b,int c,int cnt){temp[0]=a;temp[1]=b;temp[2]=c;sort(temp,temp+3);if(cnt==n){if(judge(temp[0],temp[1],temp[2])){long long state=temp[0]*10001*10001+temp[1]*10001+temp[2];if(!vis.count(state))ans++;vis[state]++;}}else {if(sum<=2*temp[2])return ;如果当前最短的两条边加上剩下的边长仍小于最长边则此方案不行不在继续搜int edge[3][3];for(int i=0;i<3;++i){edge[i][0]=a;edge[i][1]=b;edge[i][2]=c;if(i==0)edge[i][0]+=num[cnt];if(i==1)edge[i][1]+=num[cnt];if(i==2)edge[i][2]+=num[cnt];sort(edge[i],edge[i]+3);}dfs(edge[0][0],edge[0][1],edge[0][2],cnt+1);//如果当前的三条边在以前搜过就不在搜if(edge[1][0]!=edge[0][0]||edge[1][0]!=edge[0][1]||edge[1][2]!=edge[0][2])dfs(edge[1][0],edge[1][1],edge[1][2],cnt+1);if(edge[2][0]!=edge[0][0]||edge[2][1]!=edge[0][1]||edge[2][2]!=edge[0][2]){if(edge[2][0]!=edge[1][0]||edge[2][1]!=edge[1][1]||edge[2][2]!=edge[1][2])dfs(edge[2][0],edge[2][1],edge[2][2],cnt+1);}}}int main(){int t,i,j,k;scanf("%d",&t);while(t--){vis.clear();scanf("%d",&n);ans=sum=0;for(i=0;i<n;++i){scanf("%d",&num[i]);sum+=num[i];}dfs(0,0,0,0);printf("%lld\n",ans);}return 0;}


0 0
原创粉丝点击