题目
题目描述
Given a set ofi sticks of various lengths, is it possible to join them end-to-end to form a square?
输入
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 and10000.
输出
For each case, output a line containing “yes" if is is possible to form a square; otherwise output “no”".
样例输入
3
4 1 1 1 1
5 10 20 30 40 50
8 1 7 2 6 4 4 3 5
样例输出
yes
no
yes
解析
题目大意
给出一堆长度各异的木棍,这些木棍能否头尾相连形成一个正方形?
分析
题面要求判断能否搜索出一个方案让这些木棍形成正方形。首先,将木棍长度进行累加,得到总长 length;然后将 length 除以4得到正方形的边长 side;之后,将木棍拼凑成长度为 side 的边,拼凑完一条边后,再拼凑下一条,直到拼凑出4条长度为 side 的边,
从而构成一个正方形。搜索状态三元组(sum,number,position),其中 sum 是当前拼凑的木棍长度,number是已拼凑成边长的数量,position是当前木棍的编号。需要搜索到的目标状态为number=3.为什么不是4呢?因为如果总长 length 能够整除 4,且已经拼凑出3条边,那么剩下的木棍必定可以构成最后的一条边。由于从第一根木棍开始拼凑,故搜索初始状态为(0,0,0)。在搜索过程中,可以通过放弃对某些不可能产生结果的子集的搜索,达到提高效率的目的。这样的技术称为剪枝。本题中可以剪枝的途径如下:
(1)如果总长 length 不能整除 4,那么必定无法构成正方形。
(2)如果某根木棍的长度大于边长 side,那么必定无法构成正方形。(3) 拼凑中发现某长度的木棍无法构成当前边时,再遇等长木棍时可跳过(需排序)。
java代码
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
/**
* Square
* DFS: 深度优先搜索
*/
public class Square {
//访问数组
public static boolean[] isVisited;
//木棍数组
public static Integer[] array;
//木棍总长度
public static int sumLength;
//木棍数量
public static int m;
//正方形边长
public static int edgeLength;
/*
stickSum:已经拼凑的木棍总长度, stickNumber:已凑成边长的数量,
position:木棍在数组中的下标
*/
public static boolean DFS(int stickLength, int stickNumber, int position){
if (stickNumber == 3){
return true;
}
int sample = 0;
for (int i = position; i < m; i++) {
if(isVisited[i] || stickLength + array[i] > edgeLength || array[i] == sample){
continue;
}
if(stickLength + array[i] == edgeLength){
isVisited[i] = true;
if(DFS(0, stickNumber+1, 0)){
return true;
}
}else {
if(DFS(stickLength+array[i], stickNumber, position+1)){
return true;
}else {
sample = array[i];
}
}
isVisited[i] = false;
}
return false;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
for (int k = 0; k < n; k++) {
//木棍数量
m = scanner.nextInt();
//初始化访问数组
isVisited = new boolean[m];
for (int i = 0; i < m; i++) {
isVisited[i] = false;
}
//读入木棍数组
array = new Integer[m];
for (int i = 0; i < m; i++) {
array[i] = scanner.nextInt();
sumLength += array[i];
}
//对木棍进行降序排序; 实现降序就必须用包装类Integer
Arrays.sort(array, Collections.reverseOrder());
/*
剪枝: 总长度不能整除4,无法构成正方形
*/
if(sumLength % 4 != 0){
System.out.println("no");
continue;
}
/*
剪枝: 有任何一个木棍长度大于边长,无法构成正方形
edgeLength: 正方形边长
*/
edgeLength = sumLength / 4;
boolean flag = false;
for (int i = 0; i < m; i++) {
if(array[i] > edgeLength){
flag = true;
break;
}
}
if(flag){
System.out.println("no");
continue;
}
/*
进行DFS判断
*/
if(DFS(0, 0, 0)){
System.out.println("yes");
}else {
System.out.println("no");
}
}
}
}