Introduction to algorithms-steel strip cutting C # Recursive Implementation,
I saw a brother writing steel strip cutting before I got off work. I tried to implement C #. I haven't implemented the optimal version yet. Let's share it.
Int [] parr; private void button#click (object sender, EventArgs e) {// policy standard. For example, if the total length of 7 is 1st bits and 6 bits, the optimal result is: 18 = 1 + 17 parr = new int [] {1, 5, 8, 9, 10, 17, 17, 20, 45, 30 }; stack <int> stack = new Stack <int> (); // total capacity int maxLength = 7; int result = compute (parr, maxLength, ref stack); int c = stack. count; Console. writeLine ("cut:"); int temp; while (c --> 0) {Console. writeLine (temp = stack. pop ();} Console. writeLine ("result: {0}", result );}
Core part:
/// <Summary> ///// </summary> /// <param name = "p"> Policy Standard </param> /// <param name = "length"> split set </param> /// <param name = "stack"> split procedure </param> /// <returns> </returns> int compute (int [] p, int length, ref Stack <int> stack) {int price = 0; // The best solution int maxPrice = 0; // The current optimal solution step Stack <int> _ stack = null; // the temporary solution step Stack <int> _ stackTemp = null; int split; if (length = 0) return 0; for (int I = 1; I <= length; I ++) {if (I> = p. length) {split = p. length;} else {split = I;} // temporary scheme _ stackTemp = new Stack <int> (); price = p [split-1] + compute (p, length-split, ref _ stackTemp); if (maxPrice <price) {// maxPrice = price; _ stackTemp. push (split); // update the current round of optimal solution _ stack = _ stackTemp;} // Add the current round of optimal solution to the global solution set while (_ stack. count> 0) {stack. push (_ stack. pop ();} // return the optimal result return maxPrice ;}
Result: