AcWing 1224.交換瓶子 (第七屆藍橋杯省賽C++B組)

1.問題

有N個瓶子,編號1∼N,放在架子上。

好比有5個瓶子:ios

2 1 3 5 4

要求每次拿起2個瓶子,交換它們的位置。編程

通過若干次後,使得瓶子的序號爲:spa

1 2 3 4 5

對於這麼簡單的狀況,顯然,至少須要交換2次就能夠復位。code

若是瓶子更多呢?你能夠經過編程來解決。blog

輸入格式

第一行包含一個整數NN,表示瓶子數量。排序

第二行包含NN個整數,表示瓶子目前的排列情況。string

輸出格式

輸出一個正整數,表示至少交換多少次,才能完成排序。it

數據範圍

1≤N≤10000,io

輸入樣例1:

5
3 1 2 5 4

輸出樣例1:

3

輸入樣例2:

5
5 4 3 2 1

輸出樣例2:

2

2.思路

交換瓶子.jpg

3.代碼

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

const int N = 10010;

int n;
int b[N];
bool st[N];

int main()
{
    scanf("%d", &n);
    
    for (int i = 1; i <= n; i ++) scanf("%d", &b[i]);
    
    int cnt = 0;
    for (int i = 1; i <= n; i ++) 
        if (!st[i])
        {
            cnt ++;
            for (int j = i; !st[j]; j = b[j])
                st[j] = true;
        }
    printf("%d\n", n - cnt);
    
    return 0;
}
相關文章
相關標籤/搜索