Square(dfs)

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

#include <iostream>
#include <algorithm>
using namespace std;

int len[21]; // 1 - m 每个木棍的长度
bool mark[21]; // 是否使用
int m; // m个木棍
int side; // 一边长

bool isOk = 0;

// hava == 已经有的边   current 当前这条边 sum多少了    pos :
bool dfs(int have,int current,int index) {
	// 给的材料是合适的, 已经有3条边了  肯定可以的  退出吧
	if (have == 3) {
		isOk = 1;
		return true;
	}
	// 部分完成了  这条边行了,可以下一条了
	if (current == side) {
		dfs(have + 1,0,1);
	}

	for (int i = index; i <= m; i++) {
//		int next = current + len[i];
		if (mark[i] == 0 && current + len[i] <= side && isOk == 0) {
			mark[i] = 1;
			dfs(have,current + len[i],i + 1);
			mark[i] = 0;
		}

	}

}


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

int main() {
	int caseNum;
	cin >> caseNum;
	for (int caseNo = 1; caseNo <= caseNum; caseNo ++) {
		// 输入1 ~ m 边长数据
		cin >> m;
		for (int i = 1; i <= m; i ++) {
			scanf("%d",&len[i]);
			mark[i] = 0;
		}

		// 没构成正方形呢
		isOk = 0;

		//排序
		sort(len + 1, len + m + 1,compare); // 1 ~ n 排序  从大到小


		int sum = 0;
		for (int i = 1; i <= m; i++) {
			sum += len[i];
		}
		if (sum % 4 != 0) {
			cout << "no" << endl;
			continue;
		}
		side = sum / 4;
		if (len[1] > side) {
			cout << "no" << endl;
			continue;
		}

		dfs(0,0,1);
		if (isOk) {
			cout << "yes" << endl;
		} else {
			cout << "no" << endl;
		}
	}
}
发布了123 篇原创文章 · 获赞 1 · 访问量 5461

猜你喜欢

转载自blog.csdn.net/bijingrui/article/details/104810192
dfs