您的位置:首页 > 其它

hdu 1518 Square (广搜)

2013-05-06 21:31 351 查看
[align=left]Problem Description[/align]
Given a set of sticks of various lengths, is it possible to join them end-to-end to form a square?

[align=left]Input[/align]
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.

[align=left]Output[/align]
For each case, output a line containing "yes" if is is possible to form a square; otherwise output "no".

[align=left]Sample Input[/align]

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

[align=left]Sample Output[/align]

yes
no
yes

View Code

#include<iostream>
using namespace std;

int num[30] , len;
int vis[30];
int n , m;
int count;
int dfs(int start , int s , int count)
{
if(s == len)
{
if(count == 3)   //跳出递归
{return 1;}
else
{return dfs(0,0,count+1);}
}
else
{
int i;
for(i = start ; i < m; i++)
{
if(vis[i]) continue;
if(s + num[i] > len) continue;
vis[i] = 1;
if(dfs(i+1 , s + num[i] , count))
return 1;
vis[i] = 0;
}
}
return 0;
}
int main()
{
int i , sum , flag;
cin>>n;
while(n--)
{
sum = 0;
cin>>m;
count = 0;
flag = 1;
memset(vis , 0 , sizeof(vis));
for(i = 0; i < m; i++)
{
cin>>num[i];
sum += num[i];
}
if(sum % 4) {cout<<"no"<<endl; flag = 0;}
len = sum / 4;
if(flag)
{
if(dfs(0 , 0 , 0))
cout<<"yes"<<endl;
else cout<<"no"<<endl;
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: