Codeforces 335C 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.

 

题意:给你一个1~n的一个排列,一次操作是指把选一个数移动到头或尾,求使序列递增的最小操作数

思路:我们需要找一个最长的递增子序列b1,b2,b3..bm,且该子序列要满足bm = bm-1 + 1. 比如4 1 2 5 3  满足的最长递增子序列是1 2 3,那么答案最终是n -m

即我们找到这样的一个子序列后,对于其他的数,只要从小到达移到到该子序列的两端即可

r[i]表示第i大的元素,d[i]表示比i小1的数在i的左边还是右边

复制代码
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <map>
#include <set>
#include <queue>
using namespace std;
const int INF = 0x3f3f3f3f;
typedef long long ll;
const int N = 100005;
int dp[N], a[N], d[N], r[N];
int cmp(int b, int c) {
    return a[b] < a[c];
}
int main()
{
    int n;
    scanf("%d", &n);
    for(int i = 1; i <= n; ++i) scanf("%d", &a[i]);
    for(int i = 1; i <= n; ++i) r[i] = i;
    sort(r + 1, r + n + 1, cmp);
    d[1] = 1;
    for(int i = 1; i < n; ++i)
    {
        if(r[i] < r[i + 1]) d[i + 1] = 1;
        else d[i + 1] = 0;
    }
    dp[ r[1] ] = 1;
    int ans = 1;
    for(int i = 2; i <= n; ++i)
    {
        if(d[i]) dp[ r[i] ] = dp[ r[i-1] ] + 1;
        else dp[ r[i] ] = 1;
        ans = max(ans, dp[ r[i] ]);
    }
    printf("%d\n", n - ans);
    return 0;
}
View Code
复制代码

 

posted @   JL_Zhou  阅读(276)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
点击右上角即可分享
微信分享提示