HDOJ1518
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 11375 Accepted Submission(s): 3660
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 題目鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=1518
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int s[25];
int sign[25];
int sum;
int ave;
int n;
int flag;
void dfs(int t,int len ,int k)
{
int i;
if(t==5)
{
flag=1;
return;
}
if(len==ave)
{
dfs(t+1,0,0);
if(flag) return;
}
for(i=k; i<n; i++) //從前走到後
if(sign[i]==0&&s[i]+len<=ave) //標記使用了的棍子
{
sign[i]=1;
dfs(t,s[i]+len,i+1);
if(flag) return;
sign[i]=0; //回朔,沒有使用狀態恢復
}
else if(sign[i]==0&&s[i]+len>ave) return;
}
int main()
{
int i,t;
scanf("%d",&t);
while(t--)
{
sum=0;
scanf("%d",&n);
for(i=0; i<n; i++)
{
scanf("%d",&s[i]);
sum+=s[i];
}
if(sum%4!=0)//構邊的優化
{
cout<<"no"<<endl;
continue;
}
ave=sum/4;
for(i=0; i<n; i++) //有比邊長大的邊就不行
if(s[i]>ave) break;
if(i<n)
{
cout<<"no"<<endl;
continue;
}
memset(sign,0,sizeof(sign));
sort(s,s+n);
flag=0;
dfs(1,0,0);
if(flag) cout<<"yes"<<endl;
else cout<<"no"<<endl;
}
return 0;
}