1317: Square(DFS+剪枝)
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".
3 4 1 1 1 1 5 10 20 30 40 50 8 1 7 2 6 4 4 3 5
yes no yes
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
using namespace std;
int data[250],state[250];
int ave,N,M,sum;
int dfs(int x,int pos,int len)
{
int i;
if(x==3)//如果有三条边都满足,结束
return 1;
for(i=pos;i>=0;i--){
if(!state[i]){
state[i]=1;
if(len+data[i]<ave){
if(dfs(x,i-1,len+data[i]))//i-1的作用是剪枝
return 1;
}
if(len+data[i]==ave){
if(dfs(x+1,M-1,0))
return 1;
}
state[i]=0;
}
}
return 0;
}
int main ()
{
scanf("%d",&N);
while(N--){
sum=0;
memset(state,0,sizeof(state));
//memset(data,0,sizeof(data));
scanf("%d",&M);
for(int i=0;i<M;sum+=data[i],i++)
scanf("%d",&data[i]);
ave=sum/4;
if(M<4||ave*4!=sum||ave<data[M-1]){
printf("no\n");
continue;
}
if(dfs(0,M-1,0))
printf("yes\n");
else
printf("no\n");
}
return 0;
}
想的太多,做的太少。