poj 2362 Square

题目链接:poj 2362 Square

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

题意:有n个木棍,问能否拼成正方形

思路:首先n个木棍长度的和,不能被4整除则不行,输出no,反之正方形边长为len,dfs记录目前这一条边的长度l,已经拼好了几条边sum,下一条边是哪个。

#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<iostream>
using namespace std;
typedef long long ll;

int n;
int num[11000];
int vis[11000];
int sum,len;
int flag;

void dfs(int l,int sum,int pos){
	if(l==len){
		sum++;
		pos=1;
		l=0;
	}
	if(sum==4){
		flag=1;
		return ;
	}
	for(int i=pos;i<=n;i++){
		if(num[i]>len)return ;
		if(vis[i])continue;
		if(l+num[i]>len)continue;
		vis[i]=1;
		dfs(l+num[i],sum,i);
		if(flag)return ;
		vis[i]=0;
	}
}

int main(){
	int t;
	scanf("%d",&t);
	while(t--){
		scanf("%d",&n);
		sum=0;
		for(int i=1;i<=n;i++){
			scanf("%d",&num[i]);
			sum+=num[i];
		}
		if(sum%4!=0){
			printf("no\n");
			continue;
		}
		sort(num+1,num+1+n);
		reverse(num+1,num+1+n);
		len=sum/4;
		flag=0;
		memset(vis,0,sizeof(vis));
		dfs(0,0,1);
		if(flag)printf("yes\n");
		else printf("no\n");
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/yz467796454/article/details/81394548