After graduating for several years, the algorithm is still more interested in, so want to start to do the ACM problem again. I do the question more casual, generally first pick through the high rate of the problem to do.
1204th, specific description please refer to, ZOJ ACM 1204
1) Difficulty analysis
The main difficulty in this topic is to sort by length.
For example 1 2 3 4 5 6, the result must be:
1+2=31+3=41+4=51+5=62+3=52+4=61+2+3=6
But my results are:
1+2=3
1+2+3=6
1+3=6
。。。
2) Workaround
The results are cached, sorted by length, and then printed.
3) AC source code. If you want to submit directly, please delete the Chinese note.
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>//sorting algorithm override 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;" >//Description: The key, because at first did not pay attention to the problem, did not consider the input line number may be unordered, directly in ascending order. </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; Note: The comparison of the key, directly determines the algorithm's time complexity, without this judgment, the calculation timeout. 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, R ES);} return-1;}}