POJ2362 木棒组成正方形

这是一个关于POJ2362问题的C++解决方案,通过深度搜索检查一组小木棒是否能组成正方形。程序首先计算木棒总长度并判断是否为4的倍数,然后进行升序排列并递归搜索,剪枝以提高效率。如果找到正方形的四条边,输出"yes",否则输出"no"。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream>
#include<algorithm>
#include<fstream>
#include<ctime>

using namespace std;

//#define DEBUG
/* 240K	297MS */
#define MAX 64
static int len[MAX];
static int used[MAX];
static int ok;
static int sum;
static int n;
static int side;

void search_dfs(int start, int curlen, int count)/* 共有4个返回点 */
{
	if (count >= 3)
        ok = 1;
	if (ok == 1)
		return ; /* 剪枝,已经找到了*/

	for (int i = start; i < n; i++)
	{
		if (used[i])	continue;  
		int tmplen = curlen + len[i];
		if (tmplen == side) /* 已经找到一条边 */
		{
			used[i] = 1;
			search_dfs(0, 0, count + 1);
			used[i] = 0;/* 上面的搜索没有成功时,很重要*/
		}
		else if (tmplen < side) /* 不足一条边 */
		{
			used[i] = 1;
			search_dfs(i + 1, tmplen, count);
			used[i] = 0;
		}
		else  /* 超过一条边,剪枝因为边长升序排列 */
		{
			return;
		}		
	}
}


int main()
{
#ifdef DEBUG
	fstream cin("G:\\book\\algorithms\\acm\\Debug\\dat.txt");
	clock_t start, end;
	start = clock();
#endif
    int t;
	cin >> t;
	while (t-- > 0)
	{
		int i;
		cin >> n;
		for (i = 0, sum = 0; i < n; i++)
		{
			cin >> len[i];
			sum += len[i];
		}

		sort(len,len + n); //升序排列
        if (sum % 4 == 0)
		{
			side = sum / 4;	ok = 0;
			memset(used, 0, sizeof used);
			search_dfs(0, 0, 0);
			if (ok)
				printf("yes\n");
			else
				printf("no\n");
		}
		else
		{	
			printf("no\n");
		}
	}
  
#ifdef DEBUG
	end = clock();
	cout << "Time:" << (double)(end - start) / CLOCKS_PER_SEC << "S\n";
#endif

	return 0;
}

POJ2362
一组小木棒是否能够组成正方形? 使用深度搜索解决该题,总的说来思路比较简单,可以作为深度搜索类题目的一个范本进行复习。先计算出小木棒的总长,判断是否是4的整数倍。如果满足进行深度搜索,深度搜索是采用递归的方式进行设计的,注意观察递归函数的各个出口。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值