1.
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
#include
#include
#include
#include
#include
#include
#include
using namespace std;
int n,sum,flag;
int s[25],a[25];
void dfs(int num,int x,int y)//x用来记录次数,y用来记录数组下标,num与ave比较
{
if(flag) return;
if(x==4)
{
flag=1;
return;
}
if(num==sum/4)
{
dfs(0,x+1,0);
if(flag==1)
return ;
}
for(int i=y;iif(!a[i]&&(num+s[i])<=sum/4)
{
a[i]=1;
dfs(num+s[i],x,i+1);
a[i]=0;
if(flag==1)
return ;
}
}
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
sum=0;
flag=0;
memset(a,0,sizeof(a));
scanf("%d",&n);
for(int i=0;iscanf("%d",&s[i]);
sum+=s[i];
}
sort(s,s+n);
if(sum%4!=0||s[n-1]>(sum/4))
{
cout<<"no"<continue;
}
dfs(0,0,0);
if(flag==1)
cout<<"yes"<else cout<<"no"<return 0;
}
2.
乔治拿来一组等长的木棒,将它们随机地裁断,使得每一节木棍的长度都不超过50个长度单位。然后他又想把这些木棍恢复到为裁截前的状态,但忘记了初始时有多少木棒以及木棒的初始长度。请你设计一个程序,帮助乔治计算木棒的可能最小长度。每一节木棍的长度都用大于零的整数表示。
Input
输入包含多组数据,每组数据包括两行。第一行是一个不超过64的整数,表示砍断之后共有多少节木棍。第二行是截断以后,所得到的各节木棍的长度。在最后一组数据之后,是一个零。
Output
为每组数据,分别输出原始木棒的可能最小长度,每组数据占一行。
Sample Input
9
5 2 1 5 2 1 5 2 1
4
1 2 3 4
0
Sample Output
6
5
#include
#include
#include
#include
#include
#include
#include
using namespace std;
int s[70],a[70];
int flag,k;
int n,sum,m;
void dfs(int num,int x,int y)//num记录的是木棍的数目,x记录的是目前木棍的长度,y是数组下标
{
if(flag) return ;
if(num==sum/m)
{
flag=1;
return ;
}
if(x==m)
{
dfs(num+1,0,0);
if(flag) return ;
}
for(int i=y;iif(!a[i]&&x+s[i]<=m)
{
a[i]=1;
dfs(num,x+s[i],i+1);
a[i]=0;
if(flag) return ;
}
}
}
int main()
{
while(~scanf("%d",&n)&&n)
{
sum=0;
memset(a,0,sizeof(a));
flag=0;
k=0;
for(int i=0;iscanf("%d",&s[i]);
sum+=s[i];
}
sort(s,s+n);
for(m=s[n-1];m<=sum;m++)//m记载的是每个木棍的长度
{
if(sum%m!=0)
continue;
dfs(0,0,0);
if(flag)
{
cout<break;
}
}
}
return 0;
}
自己写几遍,多体会就理解了