Problem Description: Given a set of sticks of various lengths, is it possible to join them end-to-end to form a square?
Input:
4 1 1 1 1
5 10 20 30 40 50
8 1 7 2 6 4 4 3 5
Output
Yes
No
Yes
Problem Analysis:
This problem is the assignment of the i-th stick to corresponding edges. Since there are 4 edges in the square, therefore, we can assign the stick to each edge of the square. When all sticks are judged, we will compute the length of each edge. Based on such thought, corresponding implement
#include <stdio.h>
#include<string.h>
long long a[1005];
long long b[1005];
int n;
int sum;
int flag=0;
void Init(){
int i;
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%lld",&a[i]);
sum+=a[i];
}
}
void traceback(int t){
int i;
if(flag)
return ;
if(t==n){
for(i=1;i<4;i++)
if(b[i]!=sum)
return;
flag=1;
printf("yes");
return ;
}
for(i=0;i<4;i++){
b[i]+=a[t];
if(b[i]<=sum)
traceback(t+1);
b[i]-=a[t];
}
}
int main()
{
int i;
sum=0;
Init();
if(sum%4){
printf("no");
return 0;
}
sum=sum/4;
memset(b,0,sizeof(b));
traceback(0);
if(!flag)
printf("no");
return 0;
}
is tabulated as follows