【PTA] - 1067 Sort with Swap(0,*) (25 分)

  • 題意: 求只交換0這個數字,使得數集可以升序排列
  • 方法:貪心
/**
 * 貪心:
 *   1. 如果0不在本來的位置上,就將0所在位置的數與0的位置交換
 *   2.如果0在本來的位置上,就尋找一個不在本來位置上的數字與0進行交換
*/
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector>
#include <map>
#include <set>
#include <cmath>
using namespace std;
#define inf 0x3f3f3f3f
const int maxn = 100010;
int main(int argc, const char **argv)
{
    int n, t, cnt = 0, a[maxn];
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        cin >> t;
        a[t] = i;
    }
    for (int i = 1; i < n; i++)
    {
        if (i != a[i])
        {
            while (a[0] != 0)
            {
                swap(a[0], a[a[0]]);
                cnt++;
            }
            if (i != a[i])
            {
                swap(a[0], a[i]);
                cnt++;
            }
        }
    }
    cout<<cnt<<endl;
    return 0;
}
發佈了77 篇原創文章 · 獲贊 23 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章