hdu1518-dfs
Posted lijiahui-123
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了hdu1518-dfs相关的知识,希望对你有一定的参考价值。
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; } }
这里的剪枝很重要
以上是关于hdu1518-dfs的主要内容,如果未能解决你的问题,请参考以下文章
HDU4057 Rescue the Rabbit(AC自动机+状压DP)
HDU3247 Resource Archiver(AC自动机+BFS+DP)