hdoj--1518--Square(dfs)
2024-08-31 02:05:17
Square
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 11824 Accepted Submission(s): 3794
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
有n支棍子,是否可以组成一个正方形
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int s[21],n,sum,target;
bool used[21];
int cmp(int a,int b)
{
return a>b;
}
bool dfs(int curs,int curl,int pos)
{//curs:找到了几条正方形的边,curl:当前边已经拼凑的长度,只用pos之后的
if(curs==3)
return 1;//有了三条边,第四条肯定也是存在的
for(int i=pos;i<n;i++)
{
if(used[i]==true)
continue;
if(curl+s[i]==target)
{
used[i]=true;
if(dfs(curs+1,0,0)==true)//找到一条边之后就找下一条边
return true;
used[i]=false;
}
else if(curl+s[i]<target)
{
used[i]=true;
if(dfs(curs,curl+s[i],i)==true)
return true;
used[i]=false;//回溯 ,一条边可用可不用
}
}
return false;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
memset(s,0,sizeof(s));
scanf("%d",&n);
sum=0;
for(int i=0;i<n;i++)
{
scanf("%d",&s[i]);
sum+=s[i];
}
target=sum/4;
if(sum%4!=0||n<4)
cout<<"no"<<endl;
else
{
memset(used,false,sizeof(used));
sort(s,s+n,cmp);
if(target<s[0])
cout<<"no"<<endl;
else if(dfs(0,0,0)==true)
cout<<"yes"<<endl;
else
cout<<"no"<<endl;
}
}
return 0;
}
最新文章
- 十五天精通WCF——第七天 Close和Abort到底该怎么用才对得起观众
- C#报修系统Ⅱ
- jsp:forward response.sendRedirect
- javascript 动态改变onclick事件
- 基于jQuery的网站首页宽屏焦点图幻灯片
- weblogic服务器内存溢出问题解决
- Sysstat性能监控工具包中20个实用命令
- js面向对象继承
- ASP.NET aspx页面中 写C#脚本; ASP.NET 指令(<;%@%>;);
- python发送smtp 邮件 图片
- Django---路由、配置和静态文件简介
- 热更新-----为何使用lua进行热更
- CodeForces5E 环转链,dp思想
- 使用Java打印字符串表格(中英文内容不乱)
- Android Studio下加入百度地图的使用 (一)——环境搭建
- ABAP-2-会计凭证批量数据导入本地ACCESS
- Sql Server 查询库表记录数
- 零基础学python之函数与模块(附详细的代码和安装发布文件过程)
- android studio 怎么做屏幕适配?
- R 画structure图
热门文章
- UVM基础之----uvm_object
- js 学习笔记---基本概念
- 170925_1 Python socket 创建TCP的服务器端和客户端
- ASLR(Address space layout randomization)地址空间布局随机化
- Sybase_ASA 字符串拼接
- transform: scale(x,y)
- 5.Linux系统的vim与软件包管理
- Python那点事
- HTML5本地存储——Web SQL Database与indexedDB
- SIM900A 发送AT+CSTT 总是 返回Error的原因分析