hdu1518Square

本文探讨了如何通过深度优先搜索(DFS)算法解决给定木棒组合形成正方形的问题,详细介绍了输入输出规范,提供了代码实现及优化策略。

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

Square

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 9583    Accepted Submission(s): 3126


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
 
 题目类型:深搜DFS

题意: 给你一堆木棒,你能否用这些木棒(全部用完)将其拼成一个正方形,

题解:说实话我第一次这个题目不知道怎么去写,因为当时没理解题意(就算理解了能不能A掉也当令说),他说的全部用完,哎 ,不说了,待会又要抱怨我的英语了,我看的 是网上的题解,最后按照他的题解去实现自己的代码,排序一下,大的在前,小的在后,节省时间,我刚开始dfs函数只有两个参数,一个是count,代表此时完成了有几条边,还有一个是x,代表当前木棍加起来的值,加起来等于每一条边的长度后(数据给出后长度是固定的,等于数据之和除以4,如果有余数,说明不能组成正方形),count+1;此时x便清零,继续搜索,发现交掉后超时;后来加上一个w作为记录数组下标的参数,就过了,我调试代码发现w还真是有作用:因为由于排序之后,大的在前面小的在后面,w作为一个标记,就会减少时间,从而不会超时,比如这样一组数据(排序后):
12 12(0) 10(1) 8(2) 6(3) 4(4) 4(5) 3(6) 3(7) 2(8) 2(9) 1(10) 1(11);括号内代表下标,12(0)跟2(8)组合,10(1)跟4(4)组合,8(2)跟6(3)组合,接下来注意w的作用了:4(5),x=4(5),不满足等于lengh,w=5,就会从下标为5那里往后去搜索,节省了时间;  

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
using namespace std;
int M,N;
int visit[40],a[40];
int flag;		//标记
int n;			//每一组数据个数
int lengh;		//边长

int cmp(const void *a,const void *b)//排序过后大的将会在小的前面,搜索起来耗得时间也少一些
{
	return (*(int *)b - *(int *)a);
}

void dfs(int count,int x,int w)	
/*count代表边长数,x代表将那些边加起来等于lengh(x会一直逼近lengh,最后等于lengh);
为什么要加一个w参数,
*/
{
	int i;
	
	if(x==lengh)
	{
		x=0;
		w=0;
		count++;
		if(count==4)
		{
			flag=1;
			return ;
		}
	}
	for(i=w;i<n;i++)
	{
		if(!visit[i]&&x+a[i]<=lengh)
		{
			visit[i]=1;
			dfs(count,x+a[i],i);
			visit[i]=0;
		}
		if(flag)
			return ;
	}
}
int main()
{
	int T,sum,i;
	scanf("%d",&T);
	while(T--)
	{
		memset(visit,0,sizeof(visit));
		sum=0;
		scanf("%d",&n);
		for(i=0;i<n;i++)
		{
			scanf("%d",&a[i]);
			sum+=a[i];
		}
		if(sum%4!=0)	//如果不能整除4,说明不能组成正方形,因为他要将木料全部用完
		{
			printf("no\n");
			continue;
		}
		qsort(a,n,sizeof(a[0]),cmp);
		lengh=sum/4;
		if(a[0]>lengh)
		{
			printf("no\n");
			continue;
		}
		flag=0;
		//visit[0]=1;
		dfs(0,0,0);
		if(flag)
			printf("yes\n");
		else
			printf("no\n");
	}
	return 0;
	
}

/*
3
12 1 1 2 2 3 3 4 4 6 8 10 12
3
12 12 10 8 6 4 4 3 3 2 2 1 1
12 1 2 2 2 3 3 4 4 6 8 10 12
  */


 

 

     

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值