Square
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 13181 Accepted Submission(s): 4176
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
题意:输入m个数据,判断m根木棒能否能构成一个正方形,可以的话输出yes,否则输出no.
关键:深搜,有可能会超时,所以首先要剪枝,排除一部分情况,每次深搜都要把前一根木棒的下标记录下来,从后面开始搜,避免重复搜索,搜到一根木棒,则从最开始重新搜索。如果发现能够构成正方形,直接退出,通过flag的状态来判断。
代码:
#include<iostream>
#include<cstring>
using namespace std;
int m;
int a[100000];
int len;
bool flag;
bool vis[100000];
void dfs(int parent,int cnt,int num);
int main(void)
{
int n;
cin>>n;
while(n--)
{
cin>>m;
int sum=0;
int max=-1;
for(int i=0;i<m;i++)
{
cin>>a[i];
sum+=a[i];
max= max>a[i]?max:a[i];
}
if(sum%4!=0 || sum/4<max) //剪枝如果边长不为整数或边长为整数但是最长的边大于边长,则直接输出no
{
cout<<"no"<<endl;
continue;
}
len=sum/4;
memset(vis,0,sizeof(vis));
flag=false;
vis[0]=true;
dfs(0,1,0);
if(flag)
cout<<"yes"<<endl;
else
cout<<"no"<<endl;
}
return 0;
}
void dfs(int parent,int cnt,int num)
{
if(cnt==4)
{
flag=true;
return ;
}
if(num==len)
{
dfs(0,cnt+1,0);
return ;
}
for(int i=parent;i<m;i++)
{
int fnum=num+a[i];
if(fnum<=len && !vis[i])
{ vis[i]=true;
dfs(i,cnt,fnum);
if(flag) //找到以后直接退出来
return ;
vis[i]=false;
}
}
}