This algorithm can be used to solve the issue of merger stone (large data version).
Los valley topic: P5569 [SDOI2008] stones merge
For a bunch of stones (chain):
1. stone away from the start until the left to the right [k] <= stone [k + 2] and then combined stone [k + 1] + = stone [k];
2. k from moving forward until the stone [j]> stone [k] + stone [k + 1] and the number of new combined placed behind j
If no such j does not exist, on the front
3. If we can not find such k, the last two numbers on the merger that is stone [n] and stone [n - 1] (apparently the two numbers is the smallest)
4. Repeat the first step.
code show as below:
1 /* 2 2019-10-30 3 P5569 [SDOI2008]石子合并 4 czq 5 */ 6 7 #include <cstdio> 8 #include <iostream> 9 #include <algorithm> 10 using namespace std; 11 const int N = 4e4 + 10; 12 13 int n; 14 int stone[N]; 15 16 int main() 17 { 18 cin >> n; 19 for(intI = . 1 ; I <= n-; I ++) Scanf ( " % D " , & Stone [I]); 20 is 21 is // left representative of the leftmost subscript, ans recorded answer 22 is int ANS = 0 , left = . 1 ; 23 is 24 // if there are at least three rockfill midnight, i.e.,. 1-n-n-left 25 the while (left <n-- . 1 ) 26 is { 27 int K; 28 for (K = left; K <n-- . 1 ; K ++ ) 29 { 30 IF (Stone [K] <Stone = [K + 2 ]) 31 is { 32 Stone [k + . 1 ] + = Stone [k]; // merge 33 is ANS Stone + = [k + . 1 ]; // added in the answer 34 is // k on the left to the right one will overwrite k 35 for ( int J = K; J> left; J,) Stone [J] = Stone [J - . 1 ]; 36 left ++; // Since the shift to the left so plus 1 37 [ 38 is // left and up also The second step is 39 int J = K + . 1 ; 40 the while (Stone [J]> Stone [J- . 1 ] && J>left) 41 is { 42 is // exchange, the forward movement of the new combined stones 43 is the swap (Stone [J], Stone [J- . 1 ]); 44 is J - ; 45 } 46 is BREAK ; 47 } 48 } 49 // no there is K 50 IF (n-K == - . 1 ) 51 is { 52 is // rightmost stones added to the penultimate reactor, 53 is Stone [n-- . 1 ] + = Stone [n-]; 54 is //Coupled with the rightmost stones, gravel rightmost does not exist so --n 55 ANS Stone + = [- n-]; 56 is } 57 is } 58 59 // plus the remaining two piles of stones 60 ANS Stone = + [n-] + Stone [N- . 1 ]; 61 is 62 is COUT ANS << << endl; 63 is 64 return 0 ; 65 }
If the code is not read to see examples
Next, an example: Suppose there are stones piled 6: left = 1 n = 6 ans = 0 d is the number of the new merged
Code run shot:
Random example cited, is not very good, you can understand it yourself