您的位置:首页 > 其它

Square(TOJ 1398)

2009-06-14 10:50 375 查看
1398. Square

Time Limit: 2.5 Seconds Memory Limit: 65536K
Total Runs: 685 Accepted Runs: 236

Given a set of sticks of various lengths, is it possible to join them end-to-end to form a square?

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.

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


Output for Sample Input

yes
no
yes


Source: Waterloo Local Contest Sep. 21, 2002

代码:

#include<iostream>
#include<algorithm>
using namespace std;
int len[25];
int visit[25];
int each;
int n;
bool b;
int cmp(int a,int b)
{
return a>b;
}
void dfs(int i,int now,int nowlen)
{
if(now==3)
{
b=true;
return ;
}
int j;
if(b==false)
{
for(j=i;j<=n;j++)
{
if(!visit[j]&&nowlen+len[j]<=each)
{
visit[j]=1;
if(nowlen+len[j]==each)
dfs(1,now+1,0);
else
dfs(j+1,now,nowlen+len[j]);
visit[j]=0;
}
}
}
}
int main()
{
int t;
cin>>t;
while(t--)
{
cin>>n;
int i;
int sum=0;
b=false;
memset(visit,0,sizeof(visit));
for(i=1;i<=n;i++)
{
cin>>len[i];
sum+=len[i];
}
sort(len+1,len+n+1,cmp);
if(sum%4!=0)
{
cout<<"no"<<endl;
continue;
}
else
{
each=sum/4;
if(len[1]>each)
{
cout<<"no"<<endl;
continue;
}
dfs(1,0,0);//dfs(int i,int now,int nowlen),i正在用哪根棍子,已经组装了now根,当前正在组装(还没完全)的棍子长度
if(b==true)
cout<<"yes"<<endl;
else
cout<<"no"<<endl;

}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: