链接:
https://vj.e949.cn/889526602f1f7ab5e44d789392754748?v=1539700753
题意:
求最少交换次数,使得一排列成为升序。
思路:从头遍历,位置不对就交换即可。
#include <iostream>
#include <cstring>
using namespace std;
const int maxn = 2e5+10;
int a[maxn];
int pos[maxn];
int main()
{
int n;
while(cin>>n)
{
for(int i = 1; i <= n; i++)
{
cin>>a[i];
pos[a[i]] = i;
}
int ans = 0;
for(int i = 1; i <= n; i++)
{
if(a[i] != i)
{
ans++;
int pre = a[i];
swap(a[i],a[pos[i]]);
swap(pos[pre],pos[i]);
}
}
cout<<ans<<endl;
}
return 0;
}