CF1768D.Lucky Permutation

By xiaruize

思路

考虑最小需要几步可以将原序列排序。

可以建一张图,其中边为 iPii \rightarrow P_i

此时,这张图一定是若干个环,对于每个环,令它有 mm 个点,必然至少需要 m1m-1

所以,=n=K最少步数 = n - 环数 = K

那么,此时再考虑去满足题目条件,再交换任意相邻的两个即可

若相邻的两个在同一个环内,即可少做最后一次操作,需要 K1K-1

否则需要额外的一次操作,需要 K+1K+1

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/*
Name:
Author: xiaruize
Date:
*/
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define ull unsigned long long
#define ALL(a) (a).begin(), (a).end()
#define pb push_back
#define mk make_pair
#define pii pair<int, int>
#define pis pair<int, string>
#define sec second
#define fir first
#define sz(a) int((a).size())
#define rep(i, x, y) for (int i = x; i <= y; i++)
#define repp(i, x, y) for (int i = x; i >= y; i--)
#define Yes cout << "Yes" << endl
#define YES cout << "YES" << endl
#define No cout << "No" << endl
#define NO cout << "NO" << endl
#define debug(x) cerr << #x << ": " << x << endl
#define double long double
const int INF = 0x3f3f3f3f;
const int MOD = 1000000007;
const int N = 2e5 + 10;

// bool st;
int t;
int n;
int a[N];
int vis[N];
// bool en;

void solve()
{
cin >> n;
for (int i = 1; i <= n; i++)
{
vis[i] = false;
cin >> a[i];
}
bool flag = false;
int res = 0;
for (int i = 1; i <= n; i++)
{
int x = i;
if (!vis[x])
{
while (!vis[x])
{
res++;
vis[x] = i;
x = a[x];
}
res--;
}
}
for (int i = 1; i < n; i++)
{
if (vis[i] == vis[i + 1])
{
flag = true;
break;
}
}
if (flag)
res--;
else
res++;
cout << res << endl;
}

signed main()
{
// freopen(".in","r",stdin);
// freopen(".out","w",stdout);
// cerr<<(&en-&st)/1024.0/1024.0<<endl;
// auto t_1=chrono::high_resolution_clock::now();
cin >> t;
while (t--)
solve();
// auto t_2=chrono::high_resolution_clock::now();
// cout <<". Elapsed (ms): " << chrono::duration_cast<chrono::milliseconds>(t_2 - t_1).count() << endl;
return 0;
}