计蒜客-等边三角形

蒜头君手上有一些小木棍,它们长短不一,蒜头君想用这些木棍拼出一个等边三角形,并且每根木棍都要用到。 例如,蒜头君手上有长度为 11,22,33,33 的4根木棍,他可以让长度为11,22 的木棍组成一条边,另外 22 跟分别组成 22条边,拼成一个边长为 33 的等边三角形。蒜头君希望你提前告诉他能不能拼出来,免得白费功夫。
输入格式

首先输入一个整数 n(3≤n≤20),表示木棍数量,接下来输入 nn 根木棍的长度p​i​​(1≤p​i​​≤10000)。
输出格式

如果蒜头君能拼出等边三角形,输出"yes",否则输出"no"。
样例输入1

5
1 2 3 4 5

样例输出1

yes

样例输入2

4
1 1 1 1

样例输出2

no

思路:从未被选中中选择一条边,

#include<iostream>
#include<cstdio>
using namespace std;

int n,sum;
int a[101];
bool flag;
int book[101];

//x是已经组成了几条边,s是组成当前边的和,st边的索引位置
void dfs(int x,int s,int st)
{
	if(flag) return ;
	
        //已经组成3条边
	if(x == 3)
	{
		flag = true;
		return ;
	}
	
        //组成的当前边符合条件
	if(s == sum/3)
	{
		dfs(x+1,0,0);
		return ;
	}
	
	for(int i = st;i < n;++i)
    {
    	if(!book[i])
    	{
    		book[i] = 1; 
    		dfs(x,s+a[i],i+1);
    		book[i] = 0;
    	}
    	
    }
}

int main()
{
	//freopen("triangle.in","r",stdin);
	//freopen("triangle.out","w",stdout);
	cin >> n;
	for(int i = 0;i < n;++i)
	{
		 cin >> a[i];
		 sum += a[i];
	}
	
        //如果不是3的倍数,直接输出
	if(sum % 3 != 0)
	{
		cout << "no" << endl;
	}
	else
	{
		dfs(0,0,0);
		if(flag)   cout << "yes" << endl;
		else    cout << "no" << endl;		   
	}
	
	return 0;
}  


 

猜你喜欢

转载自blog.csdn.net/qq_40511966/article/details/86700850