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);
}
}
}
}
}
}*/
}
}
杭電OJ第十五屆ACM第一題 Hearthstone
Problem Description
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?
Input
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
Output
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.
Sample Input
1
120 2 3 4
Sample Output
Case #1: 40 30 24 26
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.