最少交换次数

来源:互联网 发布:淘宝侵犯肖像权扣几分 编辑:程序博客网 时间:2024/05/17 00:03

http://blog.acmol.com/category/algorithm/


第一题:现在想通过交换相邻元素的操作把一个给定序列交换成有序,最少需要交换的次数是多少?比如3 1 2 4 5需要最少交换2次。

答案:需要交换的最少次数为该序列的逆序数。

证明:可以先将最大数交换到最后,由于是相邻两个数交换,需要交换的次数为最大数后面的数的个数(可以看做是最大数的逆序数),然后,交换过后,去除最大数,再考虑当前最大数也需要其逆序数次交换。则每个数都需要交换其逆序数次操作,则总最少交换次数为序列总体的逆序数。

第二题:现在想通过交换任意两个元素的操作把一个给定序列交换成有序,最少需要交换的次数是多少?

答案:我认为是数字的总个数减去循环节的个数。

循环节的求法是,先将数组排序,然后根据之前的坐标和排序之后的坐标,构建成一个有向图,然后在这个图上找到环



对于第二题有另一种方法:

http://blog.csdn.net/yysdsyl/article/details/4311031

e.g. { 2, 3, 1, 5, 6, 4}

231564 -> 6 mismatch 
two cycles -> 123 and 456 
swap 1,2 then 2,3, then 4,5 then 5,6 -> 4 swaps to sort 
 
Probably the easiest algorithm would be to use a bitarray. Initialize it to 0, then start at the first 0. Swap the number there to the right place and put a 1 there. Continue until the current place holds the right number. Then move on to the next 0 
 
Example: 
231564 
000000 
-> swap 2,3 
321564 
010000 
-> swap 3,1 
123564 
111000 
-> continue at next 0; swap 5,6 
123654 
111010 
-> swap 6,4 
123456 
111111 
-> bitarray is all 1's, so we're done. 

 

代码:

#include <iostream>
#include <algorithm>

using namespace std;


template <typename T>
int GetMinimumSwapsForSorted(T seq[], int n)
{
    bool* right_place_flag = new bool[n];
    T* sorted_seq = new T[n];
    int p ,q;
    ////
    copy(seq, seq + n, sorted_seq);
    sort(sorted_seq, sorted_seq + n);    ////可采用效率更高的排序算法
    ////
    for(int i = 0; i < n; i++)
    {
        if(seq[i] != sorted_seq[i])
            right_place_flag[i] = false;
        else
            right_place_flag[i] = true;
    }
    ////
    p = 0;
    int minimumswap = 0;
    while(1)
    {
        while(right_place_flag[p])
            p++;
        q = p + 1;
        ////此种找法只对无重复序列能得出minimum swaps
        while(q < n)
        {
            if(!right_place_flag[q] && sorted_seq[q] == seq[p])
                break;
            q++;
        }

        if(q >= n || p >= n)
            break;
        right_place_flag[q] = true;
        if(seq[q] == sorted_seq[p])
            right_place_flag[p] = true;
        swap(seq[p], seq[q]);

        minimumswap++;
    }

    delete[] sorted_seq;
    delete[] right_place_flag;

    return minimumswap;
}


int _tmain(int argc, _TCHAR* argv[])
{
    int seq[] = {3, 2, 1, 5, 6, 8, 4, 7 };//{2,3,1,5,6,4};//{2,3,2,4,7,6,3,5};
    int n = sizeof(seq) / sizeof(int);
    cout<<"minimum swaps : "<<GetMinimumSwapsForSorted(seq, n)<<endl;

    system("pause");
 return 0;
}


也就是依次将元素放在其应该在的位置

0 0
原创粉丝点击