2018.1.29【 HDU - 1518 】解题报告(dfs,极易TLE,剪枝)

这篇博客介绍了在解决HDU的1518题目时,如何使用DFS并进行剪枝操作以避免超时错误(TLE)。作者通过自己的解题过程,强调了在简单问题中进行深度优先搜索策略和剪枝优化的重要性,并分享了一下午与TLE斗争的体会和代码反思。

Square

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


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
 

Source
 

Recommend
LL

【题目大意】

给定M个小木棍的长度,问能否组成一个正方形。

【解题思路】

题目很简单啊,思路也很简单啊,但是写出来就TLE了啊。。。如此可见dfs剪枝是多么的重要。

【解题代码】

#include <queue>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <algorithm>
using namespace std;
//dfs
const int maxn=25;
int stick[maxn]; 
bool vis[maxn];
int M,T,sum,len,flag,mmax,mmin; 
bool cmp(int a, int b)
{
	return a>b?1:0;
}
void dfs(int count,int now,int index)
{
	if(flag) return;
	if(count==4)
	{
		flag=1;
		return;
	}
	if(now==0)
	{
		dfs(count+1,len,M-1);
		if(flag)
			return;
	}
	else if(now<mmin) return;
	for(int i=index;i>=0;i--) //剪枝1:从index开始遍历 
	{
		if(!vis[i]&&now>=stick[i])
		{
			vis[i]=1;
			dfs(count,now-stick[i],i-1);	//i已经使用过 
			if(flag) return;
			vis[i]=0;
			if(index==M-1)//剪枝2(重要剪枝):由于每一边长度都相等,一边不能利用最长木棍的话,那么肯定这组数据肯定过不了,不需要检测了。
			{
				return;
			}
		//相同的忽略 
			while(stick[i]==stick[i-1]) //剪枝3:同样长度的都过不了,无需再走一遍
			{
//				printf("!1");
				i--;
			}
		}
	}
	return ;
}
int main()
{
//	freopen("in.txt","r",stdin);
	scanf("%d",&T); 
	
		while(T--)
		{
			memset(vis,0,sizeof(vis));
			scanf("%d",&M);
			flag=sum=0;
			for(int i=0;i<M;i++)
			{
				scanf("%d",&stick[i]);
				sum+=stick[i];
			}
			sort(stick,stick+M);
			mmax=stick[M-1],mmin=stick[0];
			len=sum/4;
			if(sum%4||mmax>len) printf("no\n");
			else
			{
				dfs(0,len,M-1);
				if(flag) printf("yes\n");
				else printf("no\n");
			}
			
		}
		return 0;
 } 


【收获与反思】


跟TLE斗智斗勇了一下午,慢慢嚼代码,想剪枝,确定剪枝的效果。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值