背包问题 - 分支界限

 

 

import java.util.*;
public class Main{
public static final int ASD = 1000000007;

public static void main(String[] args){

Scanner sc = new Scanner(System.in);
int k=sc.nextInt();
int a=sc.nextInt();
int x=sc.nextInt();
int b=sc.nextInt();
int y=sc.nextInt();
int sum = 0;
//k=17;a=5;x=79;b=4;y=66;
//k=205;a=1;x=92;b=4;y=92;
//3615040
sc.close();

int[] n = new int[x + y];
int[] e = new int[x + y];
for(int i = 0; i < n.length; i++){
if(i < x){
e[i] = a;
}
else{
e[i] = b;
}
n[i] = 0;
}

sum = dp(n, e, k, 0, -1);
System.out.println(sum);
}

public static int dp(int[] n, int[] e, int k, int sum, int yn){

if(meetRequire(n, e, k) == 2){ //已经超过k时之后的分支不用判断。
return sum;
}

yn = yn + 1;

n[yn] = 1;
if(yn < n.length-1){
sum = dp(n, e, k, sum, yn);
}

if(meetRequire(n, e, k) == 1){
sum = sum + 1;
}
System.out.println("" + n[0] + n[1] + n[2] + n[3] + n[4] + n[5] + " " + sum);

n[yn] = 0;
if(yn < n.length-1){
sum = dp(n, e, k, sum, yn);
}


return sum;
}


public static int meetRequire(int[] n, int[] e, int k){
int s = 0;
for(int i = 0; i < n.length; i++){
if(n[i] == 1){
s = s + e[i];
}
}
if(s < k){
//System.out.println("" + n[0] + n[1] + n[2] + n[3] + n[4] + n[5] );
return 0;
}
else if(s == k){
//System.out.println("" + n[0] + n[1] + n[2] + n[3] + n[4] + n[5] );
return 1;
}
else{
return 2;
}
}
}

递归遍历二叉树的方法- -|||

分支界限法=。=||

30%case通过率,更蠢了。。。

 

reference

https://www.bilibili.com/video/av50202822?from=search&seid=13676114442420163856

 

posted @ 2019-08-21 11:19  不咬人的兔子  阅读(368)  评论(0编辑  收藏  举报