题目:
Given a set of sticks of various lengths, is it possible to join them end-to-end to form a square?
3 4 1 1 1 1 5 10 20 30 40 50 8 1 7 2 6 4 4 3 5
yes no yes
题意 : 给你一堆木棍的长,问你能否把他们连起来成为一个正方形,注意木棍不能折断。也就是问能否把一堆数字通过相加得到4个相同的数字
思路:显然正方形的边长等于木棍长度总和除4,所以如果不整除或者木棍数量小于四或者最长的木棍比算出来的正方形边长小直接判定不可以。否则的话就根据这个求出来的边长对数列进行搜索,这个搜索没啥剪枝的,直接暴力就可以了,保存一下哪些木棍使用了就成。具体见代码。
代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
using namespace std;
typedef long long ll;
const double PI = acos(-1.0);
const double eps = 1e-6;
const int INF = 1000000000;
const int maxn = 100;
int T,n,m;
int flag,sum,len;
int sti[22];
int vis[22];
void dfs(int l,int step,int pos)
{
if(flag)
return;
if(step==4)
{
flag=1;
}
for(int i=pos;i<m;i++)
{
if(!flag&&vis[i]==0)
{
vis[i]=1;
if(sti[i]+l==len)
{
dfs(0,step+1,0);
vis[i]=0;
}
else if(sti[i]+l<len)
{
dfs(l+sti[i],step,i+1);
vis[i]=0;
}
vis[i]=0;
}
}
}
int main()
{
scanf("%d",&T);
while(T--)
{
scanf("%d",&m);
memset(vis,0,sizeof(vis));
sum=0;
for(int i=0;i<m;i++)
{
scanf("%d",&sti[i]);
sum+=sti[i];
}
sort(sti,sti+m);
len=sum/4;
flag=0;
if(sum%4||m<4||sti[m-1]>len)
printf("no\n");
else
{
dfs(0,0,0);
if(flag)
printf("yes\n");
else
printf("no\n");
}
}
return 0;
}
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
using namespace std;
typedef long long ll;
const double PI = acos(-1.0);
const double eps = 1e-6;
const int INF = 1000000000;
const int maxn = 100;
int T,n,m;
int flag,sum,len;
int sti[22];
int vis[22];
void dfs(int l,int step,int pos)
{
if(flag)
return;
if(step==4)
{
flag=1;
}
for(int i=pos;i<m;i++)
{
if(!flag&&vis[i]==0)
{
vis[i]=1;
if(sti[i]+l==len)
{
dfs(0,step+1,0);
vis[i]=0;
}
else if(sti[i]+l<len)
{
dfs(l+sti[i],step,i+1);
vis[i]=0;
}
vis[i]=0;
}
}
}
int main()
{
scanf("%d",&T);
while(T--)
{
scanf("%d",&m);
memset(vis,0,sizeof(vis));
sum=0;
for(int i=0;i<m;i++)
{
scanf("%d",&sti[i]);
sum+=sti[i];
}
sort(sti,sti+m);
len=sum/4;
flag=0;
if(sum%4||m<4||sti[m-1]>len)
printf("no\n");
else
{
dfs(0,0,0);
if(flag)
printf("yes\n");
else
printf("no\n");
}
}
return 0;
}