Square
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 6032 Accepted Submission(s): 1937
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
这题刚看时完全没思路,后来也是在膜拜了各路大神之后才恍然大悟了,这题关键还是在于深搜函数的设计,仔细结合注释看看吧
#include<stdlib.h>
int vis[25],a[25];
int sum,edge,m;
/*
# start 代表搜索数组a的起始位置
# current_length 代表当前匹配的边长长度
# cur 代表当前完成的匹配边数
*/
int dfs(int start,int current_length,int cur){
int i;
if(current_length==edge)
{//每组成一条边则判断当前组成边数是否为三,如果不为三则进行下一边长的深度匹配
return cur==3?1:dfs(0,0,cur+1);
}
else
{//当前边长如果小于正方形边长edge则继续进行深度匹配
for(i=start;i<m;i++)
{
if(!vis[i]&¤t_length+a[i]<=edge)
{//访问当前棒长并判断当前匹配长度是否达到正方形边长
vis[i]=1;//将当前访问的位置标记,防止用过的棒再次被用
if(dfs(i+1,current_length+a[i],cur))
return 1;//表示当前边匹配成功
vis[i]=0;//访问过的位置重新标记为零,方便下次搜索
}//if
}//for
}//else
return 0;
}//dfs
int main()
{
int n,i,max;
scanf("%d",&n);//测试样例组数
while(n--){
scanf("%d",&m);
max=0;//跟踪输入的最大棒长度
sum=0;
memset(vis,0,sizeof(vis));
for(i=0;i<m;i++)
{
scanf("%d",&a[i]);
max=max>a[i]?max:a[i];
sum+=a[i];
}//for
//printf("%d %d\n",sum,max);
if(sum%4||max>sum/4)//长度和不是4的倍数或最大棒长大于平均边长
printf("no\n");
else
{
edge=sum/4;
if(dfs(0,0,1))
printf("yes\n");//匹配成功
else printf("no\n");
}//else
}//while
system("pause");
return 0;
}