The minimum number of exchanges to turn a sequence into an orderly

Source: Internet
Author: User

The minimum number of interchanges to which a sequence of columns is ordered to increment or decrement.

One. Only neighboring elements can be exchanged

In this case, the minimum number of exchanges is reversed number of numbers, the number of reverse order only to traverse the array from 1~n, each time to add a number to the tree array and then the prefix and can

Two. You can swap elements at any location

For example 2 4 3 1, it can be known that 1 should be exchanged with 2, while 2 should be exchanged with 4, 4 should be exchanged with 1, so that a cycle (3 should be exchanged with itself can be regarded as self-ring), if there is a number of x in such a cycle, as long as the exchange x-1 times can be in the order of the And the different loops are not affected, so if the n number has k cycle, each cycle has the number of AI, then the number of exchanges should be (A1-1) + (a2-1) + ... + (ak-1) = N-k, that is, the number of arrays minus the number of cycles, to calculate the number of loops directly logarithmic set up diagram and then DFS again

The minimum number of exchanges to turn a sequence into an orderly

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.