USACO ORZ(dfs+set)

题目:
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

题意:
给你n条篱笆,问你可以组成多少个不同的三角形,一边不同即为不同,需要注意的是n条篱笆一起组成一个三角形,而不是在里面选3条组成一个三角形

解题思路:
利用dfs枚举出所有情况,然后利用set去掉重复的

代码:

#include <iostream>
#include <set>
using namespace std;
set<long long> d;
int s[20];
int n;
bool pd(int a,int b,int c)
{
    return ((a+b)>c && (a+c)>b && (b+c)>a);
}
void dfs(int a,int b,int c ,int t)
{
    if(n==t)
    {
        if(a==0 || b==0 || c==0)
            return ;
        if(a<=b && b<=c )
            if(pd(a,b,c))
                d.insert(a*1000001+b*200002+c*15003);//尽量让它们乘差别大的数,不然会错
        return ;
    }
    dfs(a+s[t],b,c,t+1);
    dfs(a,b+s[t],c,t+1);
    dfs(a,b,c+s[t],t+1);
}
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        d.clear();
        cin>>n;
        for(int i=0;i<n;i++)
            cin>>s[i];
        dfs(0,0,0,0);
        cout<<d.size()<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Gee_Zer/article/details/81216217