Codeforces Round #335 (Div. 2) 606C Sorting Railway Cars(hash)

来源:互联网 发布:拜尔电动牙刷知乎 编辑:程序博客网 时间:2024/06/07 18:55

C. Sorting Railway Cars
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

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 ≤ npi ≠ 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 test(s)
input
54 1 2 5 3
output
2
input
44 1 3 2
output
2
Note

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.



题目链接:点击打开链接

给出一个序列, 任一个数可以放到序列末尾或者最前, 输出最小操作数.

hash一下每个数出现的位置, n减最长连续上升长度即为答案.

AC代码:

#include "iostream"#include "cstdio"#include "cstring"#include "algorithm"#include "queue"#include "stack"#include "cmath"#include "utility"#include "map"#include "set"#include "vector"#include "list"#include "string"using namespace std;typedef long long ll;const int MOD = 1e9 + 7;const int INF = 0x3f3f3f3f;const int MAXN = 1e5 + 5;int n, len = 1, ans, a[MAXN], b[MAXN];int main(int argc, char const *argv[]){    scanf("%d", &n);    for(int i = 1; i <= n; ++i) {        scanf("%d", &a[i]);        b[a[i]] = i;    }    for(int i = 2; i <= n; ++i) {        if(b[i] > b[i - 1]) len++;        else {            ans = max(len, ans);            len = 1;        }    }    ans = max(ans, len);    printf("%d\n", n - ans);    return 0;}


1 0