CodeForces 606C Sorting Railway Cars(最长连续上升子序列) Description Input Output Examples 题意: 思路: 代码:

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.

Examples

input
5
4 1 2 5 3
output
2
input
4
4 1 3 2
output
2

题意:

一条无限长的铁路有一列由n个车厢组成的列车,编号从1到n(所有车辆的编号都是不同的),并按任意顺序排列。 小北极熊希望按照编号越来越大的顺序排列火车车厢。他一次可以让其中一车厢从它原本的地方消失,并将其传送到火车的起点,或者到达火车的尽头。 小北极熊为了对车厢进行排序需要执行的最少移动次数是多少?

思路:

求最长子序列,但是是数值连续的,比如1 3 5 7 2 4 6 8,最长数值连续上升序列为2,即1 2或者3 4或者5 6或者7 8,一定要数值连续,然后用总数减去这个数就是最后所求答案。

这个题用哈希的方法解决,特别巧妙。

代码:

#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <string>
#include <cstring>
#include <stdio.h>
#define IO ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
using namespace std;
int b[100005];
int main()
{
    IO;
    int n,a;
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        scanf("%d",&a);
        b[a]=b[a-1]+1;//核心代码
    }
    sort(b+1,b+n+1);//只是为了找最大值
    printf("%d
",n-b[n]);
}

附上另一个代码,实际两个代码思路相同~

#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <string>
#include <cstring>
#include <stdio.h>
#define IO ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
using namespace std;
int a[100050];
int main()
{
    int n;
    int i,j,k,l,max;
    while(~scanf("%d",&n))
    {
        for(i = 1; i <= n; i++)
        {
            scanf("%d",&k);
            a[k] = i;
        }
        max = 1;
        for(i = 1; i <= n-1; i+=l)
        {
            l=1;
            for(j = i+1; j <= n; j++)
            {
                if(a[j]>a[j-1])
                    l++;
                else
                    break;
            }
            if(l > max)
                max = l;
        }
        printf("%d
",n-max);
    }
    return 0;
}