hdoj--1518--Square(dfs)

Square

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 11824    Accepted Submission(s): 3794


Problem Description
Given a set of sticks of various lengths, is it possible to join them end-to-end to form a square?
 

Input
The first line of input contains N, the number of test cases. Each test case begins with an integer 4 <= M <= 20, the number of sticks. M integers follow; each gives the length of a stick - an integer between 1 and 10,000.
 

Output
For each case, output a line containing "yes" if is is possible to form a square; otherwise output "no".
 

Sample Input
   
   
   
   
3 4 1 1 1 1 5 10 20 30 40 50 8 1 7 2 6 4 4 3 5
 

Sample Output
   
   
   
   
yes no yes
 有n支棍子,是否可以组成一个正方形
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int s[21],n,sum,target;
bool used[21];
int cmp(int a,int b)
{
	return a>b;
}
bool dfs(int curs,int curl,int pos)
{//curs:找到了几条正方形的边,curl:当前边已经拼凑的长度,只用pos之后的 
	if(curs==3)
	return 1;//有了三条边,第四条肯定也是存在的 
	for(int i=pos;i<n;i++)
	{
		if(used[i]==true)
		continue;
		if(curl+s[i]==target)
		{
			used[i]=true;
			if(dfs(curs+1,0,0)==true)//找到一条边之后就找下一条边 
			return true;
			used[i]=false;
		}
		else if(curl+s[i]<target)
		{
			used[i]=true;
			if(dfs(curs,curl+s[i],i)==true)
			return true;
			used[i]=false;//回溯 ,一条边可用可不用 
		}
	}
	return false;
}
int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		memset(s,0,sizeof(s));
		scanf("%d",&n);
		sum=0;
		for(int i=0;i<n;i++)
		{
			scanf("%d",&s[i]);
			sum+=s[i];
		}
		target=sum/4;
		if(sum%4!=0||n<4)
		cout<<"no"<<endl;
		else
		{
			memset(used,false,sizeof(used));
			sort(s,s+n,cmp);
			if(target<s[0])
			cout<<"no"<<endl;
			else if(dfs(0,0,0)==true)
			cout<<"yes"<<endl;
			else
			cout<<"no"<<endl;
		}
	}
	return 0;
}



你可能感兴趣的:(hdoj--1518--Square(dfs))