hdu 4277 USACO ORZ(dfs+剪枝)

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
1
3
2 3 4
 
Sample Output
1
 
Source
 

题意:给出n条边,求围成三角行有多少种方法

直接dfs,枚举两条边x、y,并且要控制x<y,则第三边由总的减掉就好了,并且用set来标记这个三角形(使用x和y就可以了),以免重复计算

 #include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<set>
#include<algorithm>
#include<cmath>
#include<stdlib.h>
#include<map>
using namespace std;
#define ll long long
#define N 16
int n;
int a[N];
set<ll>s;
int sum;
void dfs(int x,int y,int num)
{
int z=sum-x-y;
//if(!(x<=y && y<=z))
//return;
if(num>=n)
{
if(x<=y && y<=z && x+y>z)
{
s.insert(x*10000+y);
}
return;
}
dfs(x+a[num],y,num+1);
dfs(x,y+a[num],num+1);
dfs(x,y,num+1);
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
s.clear();
scanf("%d",&n);
sum=0;
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
sum+=a[i];
}
dfs(0,0,0);
printf("%d\n",s.size());
}
return 0;
}

另一种基本上一样,用map来标记

 #include<iostream>
#include<cstdio>
#include<cstring>
#include<set>
#include<vector>
#include<map>
using namespace std;
#define N 16
int n;
int z[N];
int vis[N][N][N];
int ans;
int sum;
map<int,int>mp;
void dfs(int a,int b,int c,int num)
{
int res=sum-a-b-c;
if(a>b+c+res)
return; if(b>c+res)
return;
if(num>=n)
{
if(a>b || a>c) return;
if(b>c) return;
if(a+b>c && a+c>b && b+c>a && !mp[a*1000000+b*10+c])
{
ans++;
mp[a*1000000+b*10+c]=1;
} return;
}
dfs(a+z[num],b,c,num+1);
dfs(a,b+z[num],c,num+1);
dfs(a,b,c+z[num],num+1);
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
mp.clear();
sum=0;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d",&z[i]);
sum+=z[i];
}
ans=0;
//memset(vis,0,sizeof(vis));
dfs(0,0,0,0);
printf("%d\n",ans);
}
return 0;
}
上一篇:1102: 零起点学算法09——继续练习简单的输入和计算(a-b)


下一篇:javascript创建对象的方法--工厂模式(非常好理解)