Square
Time Limit: 3000MS | Memory Limit: 65536K | |
Total Submissions: 18900 | Accepted: 6555 |
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
Source
思路:类似sticks那道题,每次递归进去后有两种情况,(因为这里是拼四条边)(1)当前边拼好了,递归下去的时候已经拼好的
边数加1,当前正在拼的边已经拼好的长度回归0,重新从下标为0的木棍开始搜索。(2)当前木棍未拼好。。
#include<stdio.h>
#include<string.h>int sum, m, flag, len, stick[25], record[25];//m记录木棍个数,len表示正方形边长,stick记录各个木棍长度,record标记此木棍是否已经用过
void dfs(int l, int count, int num, int p){//l记录到了第几层,也就是用了几根木棍了,count记录已经拼好的边数,p记录从哪个下标开始
int i;
if(count == 4 && l == m){
flag = 1;
return ;
}
for(i = p; i < m && !flag; i++){
if(!record[i] && stick[i] <= len - num){
record[i] = 1;
if(stick[i] + num == len)//拼成一条边时
dfs(l + 1, count + 1, 0, 0);
else//还没拼成一条边时
dfs(l + 1, count, num + stick[i], i + 1);
record[i] = 0;
}
}
}
int main(){
int n, i, ans;
scanf("%d", &n);
while(n--){
scanf("%d", &m);
sum = 0;
flag = 0;
memset(record, 0, sizeof(record));
for(i = 0; i < m; i++){
scanf("%d", &stick[i]);
sum += stick[i];
}
if(sum % 4 == 0){//正方形边长一定是木棍总和除以4
len = sum / 4;
dfs(0, 0, 0, 0);
if(flag == 1)
printf("yes\n");
else
printf("no\n");
}
else
printf("no\n");
}
return 0;
}