CF1223D Sequence Sorting

Posted wangyiming

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了CF1223D Sequence Sorting相关的知识,希望对你有一定的参考价值。

思路:

首先把数组离散化,然后观察可以发现,在最优解中最终没有被移动过的那些数字一定是连续的,那么找到最长的连续的数字长度即可。

实现:

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 const int N = 300005;
 4 int a[N], l[N], r[N];
 5 int main()
 6 {
 7     int q; cin >> q;
 8     while (q--)
 9     {
10         int n; cin >> n;
11         for (int i = 0; i < n; i++) cin >> a[i];
12         vector<int> v(a, a + n);
13         sort(v.begin(), v.end());
14         v.erase(unique(v.begin(), v.end()), v.end());
15         for (int i = 0; i < n; i++)
16         {
17             a[i] = lower_bound(v.begin(), v.end(), a[i]) - v.begin() + 1;
18         }
19         int m = v.size();
20         for (int i = 1; i <= m; i++) { l[i] = n + 1; r[i] = 0; }
21         for (int i = 0; i < n; i++)
22         {
23             l[a[i]] = min(l[a[i]], i + 1);
24             r[a[i]] = max(r[a[i]], i + 1);
25         }
26         int ans = m - 1, tmp = 1;
27         for (int i = m - 1; i >= 1; i--)
28         {
29             if (r[i] < l[i + 1]) tmp++;
30             else tmp = 1;
31             ans = min(ans, m - tmp);
32         }
33         cout << ans << endl;
34     }
35     return 0;
36 }

以上是关于CF1223D Sequence Sorting的主要内容,如果未能解决你的问题,请参考以下文章

Sorting a Three-Valued Sequence

USACO Sorting a Three-Valued Sequence

Sorting a Three-Valued Sequence

CF 843 A. Sorting by Subsequences

Sorting a Three-Valued Sequence(三值的排序)

[USACO][DAG上的动态规划]Sorting A Three-Valued Sequence