HDOJ1518Square 深搜

举报
谙忆 发表于 2021/05/28 08:19:11 2021/05/28
【摘要】 Square Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 11099 Accepted Submission(s): 3566 Problem Description Given a set of st...

Square
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 11099 Accepted Submission(s): 3566

Problem 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
题意就是:看这个数组中的数字组合是否能够构成一个正方形
不能分割数字,不能重复组合

代码:

#include<string.h>
#include<stdio.h>
#include<algorithm>
using namespace std;
int n,s,su,a[1010],vis[1010],len;
bool cmp(int a,int b)
{ return a>b;//从大到小排序
}
void dfs(int a1,int a2,int a3)//(0,0,1)
{ if(a1==3)/**只需要筹齐3次,那么剩下的一定能够成len长度**/ { su=1; return ; } if(su==1) return ;/**优化时间**/ for(int i=a3; i<=n; i++) {
  /**对于那些用过的和不符合条件的,for那里可以不扫,故从a3开始**/ /**a3前面的对于最初的a2来说一定不符合**/ if(vis[i]==0) { vis[i]=1; if(a2+a[i]==len) { dfs(a1+1,0,1); /**但是换另外一条边的时候a3要改回1,因为那些未用的,对上一条边来说不符合条件的,可能符合这条边的条件**/ } else if(a2+a[i]<len) { dfs(a1,a2+a[i],i+1); /**没筹齐从i+1继续,前面的不符合**/ while(a[i]==a[i+1]) i++; //回溯后如果后面的相同那么不需要再DFS //前面的数和后面的相同就可以跳过这个数,剪枝 } vis[i]=0; } }
}

int main()
{ int i; scanf("%d",&s); while(s--) { su=0; len=0; memset(vis,0,sizeof(vis)); //memset函数在string.h头文件中 scanf("%d",&n); for(i=1; i<=n; i++) { scanf("%d",&a[i]); len=len+a[i]; } int mm=len/4; sort(a+1,a+n+1,cmp); //在algorithm头文件中 if(len%4==0&&a[1]<=mm&&n>=4) { len/=4; dfs(0,0,1); if(su==1) printf("yes\n"); else printf("no\n"); } else { printf("no\n"); } } return 0;
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80

文章来源: chenhx.blog.csdn.net,作者:谙忆,版权归原作者所有,如需转载,请联系作者。

原文链接:chenhx.blog.csdn.net/article/details/47949017

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。