hdu1518(Square)深搜+剪枝
阿新 • • 發佈:2019-01-04
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
Sample Input
3 4 1 1 1 1 5 10 20 30 40 50 8 1 7 2 6 4 4 3 5Sample Output
yes no yes題意:判斷所給的幾個數能否組成一個正四邊形
思路:從題意可以看出,要成為正四邊形,那麼必須所給的數之和能別4整除,而且所給的數中最小的數不能大於正四邊形的邊長。然後通過深搜遍歷每個數,直到組合成邊長的長度為止,最後通過統計組成邊長的個數,判斷是否滿足條件
import java.util.Scanner; public class P1518 { public static int m,edglen; public static int[] visit; public static int[] a; public static boolean flag; public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); while(n-->0){ m=sc.nextInt(); a=new int[m]; visit=new int[m]; int sum=0; flag=false; for(int i=0;i<m;i++){ a[i]=sc.nextInt(); sum+=a[i]; } if(sum%4!=0){//剪枝,總和不能被4整除,則一定不能組成 System.out.println("no"); continue; } edglen=sum/4; sort(); if(edglen<a[0]){//最小的都大於邊長,減去 System.out.println("no"); continue; } DFS(0,a[0],0); if(flag){ System.out.println("yes"); }else{ System.out.println("no"); } } } private static void DFS(int edglenNumb, int edg, int i) { int k=i; visit[i]=1; if(edg==edglen){ edglenNumb++; k=0; edg=0; } if(edglenNumb==3){ flag=true; return; } for(int j=k;j<m;j++){ if(visit[j]==0 && edg+a[j]<=edglen){ DFS(edglenNumb,a[j]+edg,j); if(flag){ return ; } } } visit[i]=0; } private static void sort() { for(int i=0;i<m-1;i++){ for(int j=0;j<m-1-i;j++){ if(a[i]>a[j]){ int t=a[i];a[i]=a[j];a[j]=t; } } } } }