• [Codeforces 606C]Sorting Railway Cars


    Description

    An infinitely long railway has a train consisting of n cars, numbered from 1 to n (the numbers of all the cars are distinct) and positioned in arbitrary order. David Blaine wants to sort the railway cars in the order of increasing numbers. In one move he can make one of the cars disappear from its place and teleport it either to the beginning of the train, or to the end of the train, at his desire. What is the minimum number of actions David Blaine needs to perform in order to sort the train?

    Input

    The first line of the input contains integer n (1 ≤ n ≤ 100 000) — the number of cars in the train.

    The second line contains n integers pi (1 ≤ pi ≤ n, pi ≠ pj if i ≠ j) — the sequence of the numbers of the cars in the train.

    Output

    Print a single integer — the minimum number of actions needed to sort the railway cars.

    Sample Input

    5
    4 1 2 5 3

    Sample Output

    2

    Hint

    In the first sample you need first to teleport the 4-th car, and then the 5-th car to the end of the train.

    题解

    首先容易注意到答案一定不会超过 $n$,因为我们只要按照大小顺序每个数都移动一次,整个序列就一定有序了,由以上结论还可以得每个数至多被移动一次。

    由于操作是将数移动到序列首部和序列尾部,那么没有被移动的数会停留在序列中部,所以这些数一定是原序列的一个子序列,并且是有序序列的一个连续子段。最小化移动即是最大化不动,那么我们找到最长的这样的一个子序列就行了。

    时间复杂度 $O(n)$ 。

     1 //It is made by Awson on 2017.10.17
     2 #include <set>
     3 #include <map>
     4 #include <cmath>
     5 #include <ctime>
     6 #include <queue>
     7 #include <stack>
     8 #include <vector>
     9 #include <cstdio>
    10 #include <string>
    11 #include <cstdlib>
    12 #include <cstring>
    13 #include <iostream>
    14 #include <algorithm>
    15 #define LL long long
    16 #define Max(a, b) ((a) > (b) ? (a) : (b))
    17 #define Min(a, b) ((a) < (b) ? (a) : (b))
    18 using namespace std;
    19 const int N = 200000;
    20 void read(int &x) {
    21   char ch = getchar(); x = 0;
    22   while (ch < '0' || ch > '9') ch = getchar();
    23   while (ch >= '0' && ch <= '9') x = (x<<1)+(x<<3)+ch-48, ch = getchar();
    24 }
    25 
    26 int n, ans, a;
    27 int f[N+5];
    28 
    29 void work() {
    30   read(n);
    31   for (int i = 1; i <= n; i++) {
    32     read(a); f[a] = f[a-1]+1;
    33     ans = Max(ans, f[a]);
    34   }
    35   printf("%d
    ", n-ans);
    36 }
    37 int main() {
    38   work();
    39   return 0;
    40 }
  • 相关阅读:
    Nacos、Apollo、SpringCloud Config微服务配置中心对比
    Mybatis四种分页方式
    如何读取resources目录下的文件路径(九种方式)
    28个Javascript数组方法,开发者的小抄
    掌握递归调用栈思想 由浅入深研究递归🎉
    「中高级前端面试」JavaScript手写代码无敌秘籍
    List<? extends T>与List<? super T>的区别
    33个非常实用的JavaScript一行代码,建议收藏!
    数组去重的六种方法
    24个 JavaScript 循环遍历方法,你都知道吗?
  • 原文地址:https://www.cnblogs.com/NaVi-Awson/p/7681131.html
Copyright © 2020-2023  润新知