Cdfpysw loves playing a card game called "Hearthstone". Now he has N cards, he wants to split these cards into 4 piles. Let‘s assume the number of cards in each pile is a1, a2, a3, a4. It must be satisfied that: a1 * k1 = a2 + a3 + a4 a2 * k2 = a1 + a3 + a4 a3 * k3 = a1 + a2 + a4 a1, a2, a3, a4 must be positive Because Cdfpysw is clever, there must be a way to split there card. Can you tell Cdfpysw what is the way?
The first line is an integer T, means the number of cases. Then T lines, each line contains 4 integers, N, k1, k2, k3, meaning of these have been shown in the description. T <= 100 1 <= N <= 109 1 <= k1, k2, k3 <= 200
For each case, you should output "Case #i: " first, i is the case number. Then output 4 integers a1, a2, a3, a4, represent the number of cards in each pile.
1 120 2 3 4
Case #1: 40 30 24 26
import java.util.Scanner; public class Hearthstone { public static int[] a = {1,1,1,1,1}; //基于深度搜索优先的回溯法 public static void DFS(int deep,int n,int[] k,int i){ if(a[1] == n) return; if(a[deep]==n){ //当子节点遍历到n,回溯 a[deep-1]++; DFS(deep-1,n,k,i); } //到第四层,若有解输出并返回,无解则继续向右 if(deep == 4){ if((a[1]+a[2]+a[3]+a[4]) == n){ System.out.println("case #"+i+": "+a[1]+" "+a[2]+" "+a[3]+" "+a[4]); return; } else{ a[deep]++; DFS(deep,n,k,i); } } //满足条件便往下搜索,不满足则剪枝 if(a[deep] < n && deep < 4){ if(a[deep]*k[deep-1] == (n-a[deep])){ DFS(deep+1,n,k,i); } else{ a[deep]++; DFS(deep,n,k,i); } } } public static void main(String[] args) { int T; int n[] = new int[100]; int k1[] = new int[100]; int k2[] = new int[100]; int k3[] = new int[100]; int a=1,b=1,c=1,d=1; Scanner scanner = new Scanner(System.in); T = scanner.nextInt(); for(int i = 1;i <= T;i++){ n[i] = scanner.nextInt(); k1[i] = scanner.nextInt(); k2[i] = scanner.nextInt(); k3[i] = scanner.nextInt(); } //对每一组实例进行求解 for(int i = 1;i <= T;i++){ int[] k = {k1[i],k2[i],k3[i]}; DFS(1,n[i],k,i); } //刚开始用的五层大循环。。醉了 /*for(int i = 1;i <= T;i++){ for(a = 1;a<=n[i];a++){ if(a*k1[i] == (n[i]-a)) for(b = 1;b<=n[i]-a;b++){ if(b*k2[i] == (n[i]-b)) for(c = 1;c<=n[i]-a-b;c++){ if(c*k3[i] == (n[i]-c)) for(d = 1;d<=n[i]-a-b-c;d++){ if((a+b+c+d) == n[i]){ System.out.println("case #"+i+": "+a+" "+b+" "+c+" "+d); } } } } } }*/ } }
原文:http://blog.csdn.net/lu_chaoqun/article/details/44707883