23 Out of 5

23 Out of 5
题目简述:
对5个给定的数,只使用+-*,这三种运算符使其计算结果为23,如果可以则输出Possible,否则输出Impossible


题目分析:

1.对于给定的5个数,需要找出所有可能的组合,即全排列,共5!种组合

2.对于给定的3种运算符,也需要给出所有可能的组合,共3^4种组合。


import java.util.Scanner;
public class Main 
{
	private final static int max = 5;
	private static boolean bool = false;
	private static int[] numbers = new int[max];
	private static Scanner s = new Scanner(System.in);
	public static void isYield23(int a[],int num,int sum)
	{
        if(num == 5)
        {
        	if(sum == 23)
        		bool = true;	
      	}
        else
        {
        	isYield23(a,num+1,sum+a[num]);
        	isYield23(a,num+1,sum-a[num]);
        	isYield23(a,num+1,sum*a[num]);
        }//All combinations of the three kinds of operators
	}
	public static void traversalNumbers(int a[],int num,int i)  
	{
	    if (i == num)
	    	isYield23(a,1,a[0]);
	    else
	        for (int k=i;k<num;k++) 
	        {
	            int tmp1 = a[i];
	            a[i] = a[k];
	            a[k] = tmp1;
	            traversalNumbers(a,num,i+1);
	            int tmp2 = a[i];
	            a[i] = a[k];
	            a[k] = tmp2;
	        }//All permutations of the five numbers
	}
	public static void main(String args[])
	{
		boolean flag = true;
		while(flag)
		{	
			int count = max;
			int index = 0;
			while(count!=0)
			{
				count--;
				numbers[index++] = s.nextInt();
			}
			if(numbers[0]==0&&numbers[1]==0&&
			numbers[2]==0&&numbers[3]==0&&numbers[4]==0)
			{
				flag = false;return;
				//Input is terminated by a line containing five zero's. 
			}
			else
				traversalNumbers(numbers,max,0);
			if(bool==true)
				System.out.println("Possible");
			else
				System.out.println("Impossible");
			bool = false;
		}
	}
}


你可能感兴趣的:(java,ACM)