ZOJ ACM 1204 (JAVA)

毕业好几年了,对算法还是比較有兴趣,所以想又一次開始做ACM题。俺做题比較任意,一般先挑通过率高的题来做。

第1204题,详细描写叙述请參考,ZOJ ACM 1204

1)难度分析

这个题目,基本的难度在于要依据长度来排序。

比方1 2 3 4 5 6。结果必须为:

1+2=3
1+3=4
1+4=5
1+5=6
2+3=5
2+4=6
1+2+3=6
可是我的结果为:

1+2=3

1+2+3=6

1+3=6

。。。

2)解决方法

将结果缓存,依据长度排序后再打印。

3)AC的源代码。假设要直接提交,请将中文凝视删除。

import java.util.Collections;  
import java.util.Comparator;  

public class Main {
	static int lineNumber;
	static int input[];
	static int M = 4;
	static boolean hasR = false;
	static java.util.ArrayList<int []> results;

	public static void main(String[] args) {
<span style="white-space:pre">		</span>//排序算法重写
		Comparator<int []> comparator = new Comparator<int []>(){  
			   public int compare(int []r1, int []r2) {  

			    if(r1[0] != r2[0]){  
			     return r1[0]-r2[0];  
			    }
			    else {
			    	return 0;
			    }
			   }
		};  
		
		java.util.Scanner scanner = new java.util.Scanner(System.in);
		
		if(scanner.hasNext()) {
			lineNumber = Integer.parseInt(scanner.nextLine());
		}
		int lineIndex = 0;
		while(scanner.hasNext()) {
			lineIndex++;
			hasR = false;
			
			String lineStr = scanner.nextLine();
			
			String strs[] = lineStr.split(" ");
			M = Integer.parseInt(strs[0]);
			input = new int[M];
			results = new java.util.ArrayList<int []>();
			
			for(int j=0; j<M;j++) {
				input[j] = Integer.parseInt(strs[j+1]);
			}
			java.util.Arrays.sort(input);       //<span style="font-family: Arial, Helvetica, sans-serif;">//说明:比較关键,由于一開始没有注意看题,没有考虑输入的一行数字可能是无序的,直接依照升序处理。</span>


			fn(0,0,0,new int[33]);
			
			if(hasR == false) {
				System.out.println("Can't find any equations.");
			} else {
				Collections.sort(results,comparator);

				for(int i = 0;i<results.size();i++) {
					int count = results.get(i)[0];
					for(int j=1;j<=count;j++) {
						System.out.print(results.get(i)[j]);
						if(j<count){
							System.out.print("+");
						}
					}
					System.out.println("="+results.get(i)[count+1]);
				}
			}
			
			System.out.println("");
			if(lineIndex == lineNumber) {
				break; 
			}
		}
	}
	
	public static long fn(int i, int sum, int count, int[] res) {
		long r;
		
		if(i==M)return -1;
		if(sum >input[M-1]) return -1;            //说明:比較关键。直接决定了算法的时间复杂度,没有这个推断。计算超时。

if (sum == input[i]) { hasR = true; res[count+1] = sum; results.add(res); } if (i < M - 1) { int res_new[] = new int[33]; for (int k = 0; k <= count + 1; k++) { res_new[k] = res[k]; } res_new[0] = count + 1; res_new[count + 1] = input[i]; fn(i + 1, sum + input[i], count + 1, res_new); fn(i + 1, sum, count, res); } return -1; } }





原文地址:https://www.cnblogs.com/zsychanpin/p/7027574.html