这个题是P1011 stick 的简单版,以前都是参考着别人的代码才AC的、。
今天我就费了很多的时间,一直以为自己是对的,然后看了一下我以前写的,
发现自己存在着一个误区:一个边一个边的搜索到。其实要全部一直才可以的。
因为这里的组合不是想像中的那么的简单。
注意:在变量比较多的时候还是要把变量写得明确一点,不要为了节约一点时间而浪费更多时间。
#include <stdio.h>
#include <string.h>
#include<iostream>
#include <algorithm>
using namespace std;
int used[100],len[100],sum,n,Min,s[100];
bool f;
void find(int i,int left,int s)
{
//cout<<i<<' '<<left<<' '<<s<<endl;
int j,k;
if (s==0)
{
f=true;
return ;
}
if (s<0)
return ;
for (j=i;j<=n;j++) if (!used[j])
{
used[j]=1;
if (left==len[j])
{
//cout<<left<<' '<<j<< ' '<<s<<endl;
//cout<<j<<"yes";
find(1,sum/4,s-left);
}
else if (left>len[j])
{
find(j+1,left-len[j],s-len[j]);
}
used[j]=0;
if (len[j]==left)
return;
if (f)
return;
while (len[j+1]==len[j])
j++;
}
}
bool cmp(int a,int b) {return a>b;}
int main()
{
freopen("in.txt","r",stdin);
int i;
int t;
cin>>t;
while (t--)
{
cin>>n;
for (i=1;i<=n;i++)
scanf("%d",&len[i]);
memset(used,0,sizeof(used));
sort(len+1,len+n+1,cmp);
sum=0;
for (i=1;i<=n;i++) sum+=len[i];
if (sum%4 || len[1]>sum/4)
{
puts("no");
continue;
}
Min=4;
len[n+1]=0;
f=false;
(find(1,sum/4,sum));
if (f)
{
puts("yes");
}
else
puts("no");
}
return 0;
}
Square
Time Limit: 3000MS | Memory Limit: 65536K | |
Total Submissions: 16128 | Accepted: 5559 |
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