Codeforces Round #335 (Div. 2) C. Sorting Railway Cars 最长连续上升子序列

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
5
4 1 2 5 3
output
2
input
4
4 1 3 2
output
2
题意:给你一个序列,你可以将序列中的任意一个数取出来放到序列的第一位或者最后一位,问你最少多少次就可以把该序列转换成一个递增的序列。

思路:从后向前遍历,假如现在 遍历到了a[k],那么寻找a[k]+1,而a[k]+1已经在之前做了类似操作,依次类推就能找到以a[k]为起点的最长上升子序列了。

代码:
#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <cstring>
using namespace std;
#define inf 0x3f3f3f3f
#define maxn 100011
typedef long long ll;
int a[maxn],dp[maxn];
//dp[k]代表以k为起点的最长连续上升子序列的长度
int main()
{
#ifdef CDZSC_June
    freopen("t.txt","r",stdin);
#endif
    int n;
    while(~scanf("%d",&n))
    {
        for(int i = 1; i<= n; i++)
        {
            scanf("%d",&a[i]);
            dp[i] = 0;
        }
        dp[n+1] = 0;
        for(int i = n; i>= 1; i--)
        {
            dp[a[i]] = dp[a[i] + 1] +1;
        }
        sort(dp+1,dp+n+1);//排序找到最大值
        printf("%d\n",n - dp[n]);
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值