zoukankan      html  css  js  c++  java
  • [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 }
  • 相关阅读:
    深入浅出Java三大框架SSH与MVC的设计模式
    excel 日期/数字格式不生效需要但双击才会生效的解决办法
    如何隐藏DIV对象
    使用 Arrays 类操作 Java 中的数组
    Java常量的应用
    Windows操作系统下tomcat安装版图文教程
    命名sql数据集
    【转载】如何写一个框架:步骤(下)
    【转载】如何写一个框架:步骤(上)
    C++Builder实现二分查找法
  • 原文地址:https://www.cnblogs.com/NaVi-Awson/p/7681131.html
Copyright © 2011-2022 走看看