Finding solution for pancake sort efficiently without actually flipping each time Problem

Solve correct flips to sort given input with pancake sort.

Example

input (input size and values):
8
6 7 2 5 1 4 3 8

solution (number of flips and how many elements to flip per operation):
6
2 7 4 5 3 4

    2 -&gt; 7 6 2 5 1 4 3 8 
    7 -&gt; 3 4 1 5 2 6 7 8 
    4 -&gt; 5 1 4 3 2 6 7 8 
    5 -&gt; 2 3 4 1 5 6 7 8 
    3 -&gt; 4 3 2 1 5 6 7 8 
    4 -&gt; 1 2 3 4 5 6 7 8 

alternative solution:
6
3 6 2 5 7 3


Program doesn't need to actually sort anything, just give one possible solution.

What would be faster way to calculate needed flips without resorting to sorting input with ineffective pancake sort?

#include &lt;iostream&gt;
#include &lt;algorithm&gt;
#include &lt;vector&gt;


int main() {
    using namespace std;
    ios::sync_with_stdio(false);

    int N;
    cin &gt;&gt; N;
    vector&lt;int&gt; v(N);
    vector&lt;int&gt; flips;

    for (int i=0; i&lt;N; ++i)
        cin &gt;&gt; v[i];

    auto first  = v.begin();
    auto last   = v.end();
    for (; first != last; --last)
    {
        auto mid = max_element(first, last);
        if (mid == last - 1) {
            continue;
        }
        if (first != mid) {
            flips.push_back(distance(first, mid+1));
            reverse(first, mid + 1);
        }
        flips.push_back(distance(first, last));
        reverse(first, last);
    }

    cout &lt;&lt; flips.size() &lt;&lt; endl;
    for (auto flip : flips)
        cout &lt;&lt; flip &lt;&lt; " ";
    cout &lt;&lt; endl;
}
You should drop namespace std; It is bad practice even in challenges.
Use more descriptive names even if the variable is named so in the problem. You can also use a range based loop for the initialization of the elements.

size_t vectorLength;
std::cin &gt;&gt; vectorLength;
std::vector&lt;int&gt; numbers(vectorLength);    
for (auto &amp;number : numbers) {
    std::cin &gt;&gt; number;
}

You declare the iterators outside of the loop, which is uneccessary, if both have the same type.

for (auto first  = v.begin(), last = v.end(); first != last; --last)


Also you iterate from the end so you might want to think about using reverse iterators aka rbegin() and rend()
When comparing or increasing iterators, you should use mid == std::next(last, 1) and or std::prev accordingly. This works with every kind of iterator. 


This also brings me to the bad choice of your loop variable. the iterator is called last and you compare with std::next(last, 1), which one would expect to be out of memory access. Instead define an explicit iterator auto it = numbers.end() and use it in your loop, avoiding confusion.