POJ 2362:Square 觉得这才算深度搜索

Square
Time Limit: 3000MS Memory Limit: 65536K
Total Submissions: 21821 Accepted: 7624

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


这个题和POJ1011觉得真的是两道特别棒的题目,仔细琢磨很有味道。这个题一开始输出大写的YES和NO导致WA了一次。。。

题意是给你M根木棒,接下来给你每根木棒的长度,问这些木棒是否能够构成一个正方形。

具体理解见代码:

#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <string>
#include <cstring>
#pragma warning(disable:4996)
using namespace std;

int num_s,flag,sum;
int stick[25];
bool visit[25];

bool dfs(int num,int length,int stick_st,int * stick,bool *visit)
{
	if(num==4)
		return true;
	int i;
	for(i=stick_st;i<=num_s;i++)
	{
		if(visit[i])continue;

		visit[i]=true;
		if(length+stick[i]<(sum/4))
		{
			if(dfs(num,length+stick[i],i+1,stick,visit))
			{
				return true;
			}
		}
		else if(length+stick[i]==(sum/4))
		{
			if(dfs(num+1,0,1,stick,visit))
			{
				return true;
			}
		}
		visit[i]=false;
	}
	return false;
}

bool cmp(const int a,const int b)
{
	return a>b;
}

int main()
{
	int Test,i;
	cin>>Test;

	while(Test--)
	{
		cin>>num_s;
		sum=0;
		flag=0;
		for(i=1;i<=num_s;i++)
		{
			cin>>stick[i];
			visit[i]=false;
			sum += stick[i];
		}
		if(num_s<4||sum%4)//剪枝1:如果木棒数量小于4,cut。
		                  //剪枝2:如果sum的和不能整除4,cut。
		{
			cout<<"no"<<endl;
		}
		else
		{
			sort(stick+1,stick+1+num_s,cmp);
			if(stick[1]>sum/4)//剪枝3:如果最大的一根木棒大于了sum/4,cut。
				cout<<"no"<<endl;
			else
			{
				if(dfs(1,0,1,stick,visit))//第一个数代表当前要完成的第几根木棒
				                          //第二个数代表当前已经完成的长度
				                          //第三个数代表从第几个木棒开始查找的
				{
					cout<<"yes"<<endl;
				}
				else
				{
					cout<<"no"<<endl;
				}
			}
		}
	}
	return 0;
}




版权声明:本文为博主原创文章,未经博主允许不得转载。

转载于:https://www.cnblogs.com/lightspeedsmallson/p/4785813.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值