newcoder61132F <结论:排序最小交换次数>

题目

松鼠排序
n个不同的数,任意交换位置进行排序,其最小交换次数。

思路

结论:=nr,其中r为置换环个数。
参考:https://www.cnblogs.com/CDOI-24374/p/16410082.html

代码

Code

#include <iostream>
#include <algorithm>
#include <vector>
#include <cstring>
using namespace std;
using LL = long long;
const int N = 1e5 + 10;
vector<int> adj[N];
bool vis[N];

void dfs(int u)
{
    vis[u] = true;
    for (auto v: adj[u]) if (!vis[v]) dfs(v);
}

void solv()
{
    int n;
    cin >> n;
    for (int i = 1, a; i <= n; i ++)
    {
        cin >> a;
        adj[a].push_back(i);
    }
    int cnt = 0;
    for (int i = 1; i <= n; i ++)
        if (!vis[i])
        {
            cnt ++;
            dfs(i);
        }
    cout << n - cnt << endl;
}

int main()
{
    ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    int T = 1;
	// cin >> T;
    while (T --)
    {
        solv();
    }
    return 0;
}

posted @   O2iginal  阅读(10)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示