Backfront AtCoder - 3959 (最长连续上升序列)

You are given a sequence (P1,P2,…,PN) which is a permutation of the integers from 1 through N. You would like to sort this sequence in ascending order by repeating the following operation:

  • Choose an element in the sequence and move it to the beginning or the end of the sequence.

Find the minimum number of operations required. It can be proved that it is actually possible to sort the sequence using this operation.

Constraints

  • 1N2×105
  • (P1,P2,…,PN) is a permutation of (1,2,…,N).
  • All values in input are integers.
Input

Input is given from Standard Input in the following format:

N
P1
:
PN
Output

Print the minimum number of operations required.

Sample Input 1

4
1
3
2
4
Sample Output 1

2

For example, the sequence can be sorted in ascending order as follows:

  • Move 2 to the beginning. The sequence is now (2,1,3,4).
  • Move 1 to the beginning. The sequence is now (1,2,3,4).
Sample Input 2

6
3
2
5
1
4
6
Sample Output 2

4
Sample Input 3

8
6
3
1
2
7
4
8
5
Sample Output 3

5

这个题是可以 既往后放,又可以往前放。

我一开始就想的是逆序对,结果逆序对只可以只往一个方向放,不能既往前放,又往后放。4 2 3  1,是个反例

所以用最长上升序列。找到最长的一个,其他的不往后放,就往前放。  n-len 就行,找最小的一个。




#include <cstdio>
#include<cstring>
#include <algorithm>
using  namespace std;
#define mem(v,x) memset(v,x,sizeof(v))
#define low(x) (x & (-x))
int pos[500010],n,m;

int main() {
    scanf("%d",&n);
    for (int i = 1; i <= n; i++){
       scanf("%d",&m);
       pos[m] = i;
    }
    int len = 1,ans = 5000000;
    for (int i = 1; i < n; i++){
        if (pos[i+1] > pos[i]) len++; else{
            ans = min(ans,n-len);
            len = 1;
        }
    }
    ans = min(ans,n-len);
    printf("%d\n",ans);

    return 0;
}

猜你喜欢

转载自blog.csdn.net/kidsummer/article/details/80491527