您的位置:首页 > 大数据 > 人工智能

Codeforces Round #335 (Div. 2) 605A Sorting Railway Cars

2015-12-10 20:56 447 查看
A. 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 ≤ 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 test(s)

input
5
4 1 2 5 3


output
2


input
4
4 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.

题目大意是给定n个数,然后升序排序,但是排序只能将一个数扔到数列头或者尾,问这么升序排序最少要多少次移动元素

官方题解:

605A
- Sorting Railway Cars. Let’s suppose we removed from the array all that elements we would move. What remains?
The sequence of the numbers in a row: a, a+1, …, b. The length of this sequence must be maximal to minimize the number of elements to move. Consider the array pos, where pos[p[i]] = i. Look at it’s subsegment pos[a], pos[a+1], …, pos[b]. This sequence must
be increasing and its length as mentioned above must be maximal.

思路是找原数列中只看相对的前后位置的每次递增1的上升子序列

如第一个示例是1 2 3长度为3

第二个是1 2长度为2注意必须是连续的,假如有1 2 4 3,那么是1 2 3而不是1 2 4

方法是将原来的每个数p[i]的位置存入pos,第一个示例

pos 1 2 3 4 5

2 3 5 1 4

然后在这个pos数组中找连续相邻的最长上升子序列的长度,然后最后输出:n - 最大长度

如这个的相邻且连续的上升子序列是23 5,长度为3,输出5 - 3 = 2这么做的原因是,只要找到一个最长的相邻且连续的上升子序列(也就是在原数列中相对的前后位置是小的在前,大的在后,可能中间隔着几个元素),然后剩下的元素使劲往两头扔就行了,还剩多少个元素就扔多少次

#include <cstdio>
#include <iostream>
#include <algorithm>

using namespace std;

const int maxn = 100010;

int pos[maxn];

int main()
{
int n, tem;
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d", &tem);
pos[tem] = i;
}
int cou = 0, MAX = -1;
for (int i = 1; i <= n; i++) {
if (i == 1) {  ////注意前后边界
cou++;
MAX = 1;
}
else if (pos[i] > pos[i - 1]) {
cou++;
MAX = max(MAX, cou);   //注意前后边界
}
else {
MAX = max(MAX, cou);
cou = 1;
}
}
printf("%d\n", n - MAX);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: