1. 程式人生 > >CTU2107-H-Dark Ride with Monsters

CTU2107-H-Dark Ride with Monsters

%d its freopen sca include 求和 != open swap

Dark Ride with Monsters

題意:一串數字從兩兩交換使最後的順序能從1~N問最少需要交換幾次

思路:從第一個數字出發進行位置交換直到最後數字出現在正確的位置上,記下每個位置數字需要交換的次數最後求和。

#include<bits/stdc++.h>
using namespace std;
const int maxn=2*1e5+10;
int N;
int a[maxn],b[maxn];
int main()
{
    //freopen("in.txt","r",stdin);
    int i;
    while(~scanf("%d",&N))
    {
        for(i=1; i<=N; i++)scanf("%d",&a[i]);
        int ans=0;
        for(int i=1; i<=N; i++)
        {
            int cnt=0;
            while(a[i]!=i)
            {
               swap(a[a[i]],a[i]);
               cnt++;
            }
            ans+=cnt;
        }
        printf("%d\n",ans);
    }
    return 0;
}

CTU2107-H-Dark Ride with Monsters