A1581 Square ( DFS(深度优先搜索))

2014-11-24 09:49:31 · 作者: · 浏览: 3

Square
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 6032 Accepted Submission(s): 1937


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

题目大意:是否可以组成一个正方形
思路: DFS 算法

import java.io.*;
import java.util.*;
public class Main {
	public static boolean mark[];
	public static Integer a[];
	public static boolean boo;
	public static int edge,sum;
	public static int n,m;
	public static void main(String[] args) {
		Scanner sc=new Scanner(new BufferedInputStream(System.in));
		PrintWriter pw=new PrintWriter( new BufferedOutputStream(System.out),true);
			n=sc.nextInt();
			for(int i=0;i(){//排序
					public int compare(Integer o1, Integer o2) {
						return o1>o2 -1:1;//按降序排序
					}
					
				});
				edge=sum>>2;//右一位除以2
				if(sum%4==0&&edge>=a[0]){
					DFS(0,0,0);
					if(boo)
						pw.println("yes");
					else
						pw.println("no");
				}else{
					pw.println("no");
				}
		}
			
	}
	// 第一个变量是有几条边,第二个变量是每次循环边长的大小, 第三个变量是第几个元素
	public static void DFS(int length,int size,int index){
		//如果为真就返回
		if(boo)
			return;
		//等于四条边就退出循环
		if(length==4){
			boo=true;
		}
		if(size==edge){
			DFS(length+1,0,length+1);
		}
		else{
			for(int i=index;i 
 
import java.io.*;
import java.util.*;
public class Main {
	public static int n,m,sum,edge;
	public static boolean mark[];
	public static int a[];
	public static void main(String[] args) {
		Scanner sc=new Scanner(new BufferedInputStream(System.in));
		PrintWriter pw=new PrintWriter(new BufferedOutputStream(System.out),true);
		n=sc.nextInt();
		for(int i=0;i>2;//右移一位除以2
			Arrays.sort(a);//排序
			if(sum%4==0&&edge>=a[a.length-1]){//边长要大于等于数组里里面的元素的最大值
				if(DFS(0,0,0))
					pw.println("yes");
				else
					pw.println("no");
			}else
				pw.println("no");
		}
	}
	// 第一个变量是有几条边,第二个变量是每次循环边长的大小, 第三个变量是第几个元素
	public static boolean DFS(int length,int size,int index){
		//等于四条边的就退出循环
		if(length==4)
			return true;
		if(size==edge){
			if(DFS(length+1,0,length+1))
				return true;
			else
				return false;
		}
		else{
			for(int i=index;i