回溯法Square
来源:互联网 发布:高级美工培训 编辑:程序博客网 时间:2024/06/16 22:27
Square
Description
Given a set ofsticks of various lengths, is it possible to join them end-to-end to form asquare?
Input
The first line ofinput contains N, the number of test cases. Each test case begins with aninteger 4 <= M <= 20, the number of sticks. M integers follow; each givesthe 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<iostream>
#include<algorithm>
using namespace std;
#define maxM 20 //M的Ì?最Á?大䨮值¦Ì
struct Node
{
int key;//记?录?输º?入¨?的Ì?值¦Ì
bool visit;//记?录?是º?否¤?访¤?问¨º过y
};
Node node[maxM+1];
bool square(int i,int cur,int count,int ave);
int main()
{
int N;
cin>>N;
while(N>0)
{
int M;
cin>>M;
node[0].key=M;
intsum=0;//总Á¨¹和¨ª
intavg=0;//平?均¨´数ºy
boolflag=false;//成¨¦功|与®?否¤?的Ì?标À¨º识º?
for(int i=1;i<M+1;i++)
{
cin>>node[i].key;
node[i].visit=false;
sum+=node[i].key;
}
if(sum%4!=0)
{
flag=false;
}
else
{
avg=sum/4;
flag=square(1,0,0,avg);
}
if(flag)
cout<<"yes"<<endl;
else
cout<<"no"<<endl;
N-=1;
}
return 0;
}
bool square(int i,int cur,int count,int ave)
{
if(cur==ave)
{
count+=1;
if(count==4)
returntrue;
i=1;
cur=0;
}
for(int j=i;j<=node[0].key;j++)
{
if(!node[j].visit)
{
node[j].visit=true;
if(((cur+node[j].key)<=ave)&&square(j+1,cur+node[j].key,count,ave))
returntrue;
node[j].visit=false;
}
}
return false;
}
回溯法的关键在于写递归函数
- 回溯法Square
- 回溯法——Ural 1073 Square Country
- HDU 1518 Square(回溯)
- POJ 2362 Square(DFS回溯构造)
- POJ 2362 Square 经典DFS回溯
- 杭电 1518 Square (深搜)(回溯)
- HDU 1518 Square(回溯搜索,减枝很巧妙啊)
- 回溯法
- 回溯法
- 回溯法
- 回溯法
- 回溯法
- 回溯法
- 回溯法
- 回溯法
- 回溯法
- 回溯法
- 回溯法
- 真·为WordPress添加自机LaTeX支持(LaTeX for WordPress+MathJax)
- Linux僵尸进程
- hibernate学习笔记(一)hibernate应用背景(为什么要用hibernate)
- 数据结构之栈
- axis生成web服务
- 回溯法Square
- Chrome开发者工具调试
- Looper,Handler和Message。
- markdown模板
- leetcode_First Bad Version
- IOS数据持久性保存之CodeData的使用
- 函数(栈)帧
- 传智播客javase总结 8
- C++学习之模板:模板重载