POJ2362_Square_深搜

Square
Time Limit: 3000MS Memory Limit: 65536K
Total Submissions: 24319 Accepted: 8378

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


大致题意:

给出数根已知长度的木棍,问把这些木棍都用上,能不能构成一个正方形。


大致思路:

先把木棍从大到小排序,然后进行带回溯的深搜。

三个剪枝:1)长度相等的木棍,前面的没用上,后面的就不用试了。 2)拼一条边放的第一根木棍不行,说明这根木棍到最后也用不上,肯定不能拼成正方形。 3)拼同一条边的过程中,按从长到短的顺序放木棍。


解题过程:

WA了好几个小时,就因为两个语句写反了,导致拼好一条边后,这条边就不能被拆开了。


#include<cstdio>
#include<algorithm>

int stk [25];
bool usd [25];
int cas,n,sum;

bool dfs (int now,int pos,int cpl)
{
	if(now==sum) now=0,pos=0,cpl++;
	if(cpl==4) return 1;

	for(int i=pos;i<n;i++){

		if(stk[i]+now>sum||usd[i]) continue;
		if(i>0&&stk[i]==stk[i-1]&&!usd[i-1]) continue;

		usd[i]=1;
		if(dfs(now+stk[i],i+1,cpl)) return 1;
		usd[i]=0;//超级超级超级WA点
		if(now==0) return 0;
	}

	return 0;
}

bool cmp (int x,int y)
{
	return x>y;
}

int main ()
{
	//freopen("in.txt","r",stdin);

	scanf("%d",&cas);
	while(cas--){

		scanf("%d",&n);
		sum=0;
		for(int i=0;i<n;i++){
			scanf("%d",stk+i);
			sum+=stk[i];
		}

		if(!(sum%4)) sum/=4;
		else{
			printf("no\n");
			continue;
		}

		std::sort(stk,stk+n,cmp);

		if(dfs(0,0,0)) printf("yes\n");
		else printf("no\n");

		for(int i=0;i<n;i++)
			usd[i]=0;

	}

	return 0;

}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值