标签:-- compare code port stat print next rri length
import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; public class hdu1518DFS{ private static boolean [] vis; private static Integer [] array; private static int edge; public static void main(String[] args) { Scanner in = new Scanner(System.in); int cases,n,sum; cases = in.nextInt(); while(cases-->0){ n = in.nextInt(); sum = 0; vis = new boolean[n]; array = new Integer[n]; for(int i = 0; i < array.length; ++i){ array[i] = in.nextInt(); sum += array[i]; } edge = sum >>2;//sum/4 if(sum%4 == 0 && edge >= array[0]){ //剪枝,在剪枝后再进行操作会减少运行时间 Arrays.sort(array,new Comparator<Integer>(){ //从大到小排序 @Override public int compare(Integer o1, Integer o2){ return o2-o1; } }); if(dfs(0,0,0)){ System.out.println("yes"); }else{ System.out.println("no"); } }else{ System.out.println("no"); } } } private static boolean dfs(int curLen, int num, int cur){ if(num == 3){ return true; } if(curLen == edge){ if(dfs(0,num+1,num+1)){ return true; }else{ return false; } }else{ for(int i = cur; i < array.length; ++i){ if(!vis[i] && curLen+array[i] <= edge){ vis[i] = true; if(dfs(curLen+array[i],num,i+1)){ //这里时重点,大幅减小搜索范围 return true; } vis[i] = false; } } } return false; } }
这里的剪枝很重要
标签:-- compare code port stat print next rri length
原文地址:https://www.cnblogs.com/lijiahui-123/p/13380035.html