|
| 1 | +Notice that the sum of the whole set remains invariant through the process. |
| 2 | + |
| 3 | +Begin at the initial cake, and perform the operation on the largest piece presently in the set. |
| 4 | + |
| 5 | +If the largest element is already present in the original, then discard it and move on to the next greatest element. |
| 6 | + |
| 7 | +If the largest element in our set is smaller than the largest element we have not yet reached in the given array, |
| 8 | +it is not possible. |
| 9 | + |
| 10 | +---- |
| 11 | + |
| 12 | +Please note that it is not possible to begin with the final array and greedily merge the smallest two elements |
| 13 | +and see if we finish at the final array |
| 14 | + |
| 15 | +Here is the counter example - |
| 16 | + |
| 17 | +6 |
| 18 | +1 1 1 1 1 1 |
| 19 | + |
| 20 | +Step 1 - 2 1 1 1 1 |
| 21 | +Step 2 - 2 2 1 1 |
| 22 | +Step 3 - 2 2 2 |
| 23 | +Step 4 - 4 2 |
| 24 | +Step 5 - |
| 25 | +Not possible |
| 26 | + |
| 27 | +But, actually |
| 28 | + |
| 29 | +Step 1 - 2 1 1 1 1 |
| 30 | +Step 2 - 3 1 1 1 |
| 31 | +Step 3 - 3 2 1 |
| 32 | +Step 4 - 3 3 |
| 33 | +Step 5 - 6 |
| 34 | + |
| 35 | +It is possible |
| 36 | + |
| 37 | +It is not always optimal to merge smallest 2 |
| 38 | + |
| 39 | +------ |
| 40 | + |
| 41 | +void solve() |
| 42 | +{ |
| 43 | + int no_of_elements; |
| 44 | + cin >> no_of_elements; |
| 45 | + |
| 46 | + long long sum = 0, minimum = 1e12, maximum = 0; |
| 47 | + multiset <long long> S, original_S; |
| 48 | + vector <long long> A(no_of_elements + 1); |
| 49 | + for(int i = 1; i <= no_of_elements; i++) |
| 50 | + { |
| 51 | + cin >> A[i]; |
| 52 | + |
| 53 | + original_S.insert(A[i]); |
| 54 | + |
| 55 | + sum += A[i]; |
| 56 | + minimum = min(minimum, A[i]); |
| 57 | + maximum = max(maximum, A[i]); |
| 58 | + } |
| 59 | + |
| 60 | + S.insert(sum); |
| 61 | + |
| 62 | + int possible = true; |
| 63 | + while(S.size() > 0 && *(S.begin()) >= minimum && *(S.rbegin()) >= *(original_S.rbegin())) |
| 64 | + { |
| 65 | + auto it1 = (S.rbegin()); |
| 66 | + long long x = *it1; |
| 67 | + |
| 68 | + if(original_S.count(x) > 0) |
| 69 | + { |
| 70 | + original_S.erase(original_S.find(x)); |
| 71 | + S.erase(S.find(x)); |
| 72 | + |
| 73 | + continue; |
| 74 | + } |
| 75 | + |
| 76 | + S.erase(S.find(x)); |
| 77 | + long long new_x = x/2, new_y = x/2 + (x%2 != 0); |
| 78 | + |
| 79 | + |
| 80 | + S.insert(new_x); |
| 81 | + S.insert(new_y); |
| 82 | + } |
| 83 | + |
| 84 | + possible = (S.size() == 0); |
| 85 | + |
| 86 | + cout << (possible ? "YES" : "NO") << "\n"; |
| 87 | +} |
0 commit comments