Codeforces 605A Sorting Railway Cars [贪心]

来源:互联网 发布:加工中心钻孔手动编程 编辑:程序博客网 时间:2024/04/30 19:55

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.

Examples
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.


由于可以将中间一个放到队首和队尾,并且每个数最多被操作一次才能保证最优,所以让尽量少的数不动,i.e.让尽量多的连续数值的数不动。开个表O(n)递推即可。

#include<iostream>#include<cstdio>#include<cstring>#include<cstdlib>#include<cmath>#include<vector>#include<queue>#include<stack>#include<map>#include<set>#include<string>#include<iomanip>#include<ctime>#include<climits>#include<cctype>#include<algorithm>#define AUTO "%I64d"using namespace std;#define smax(x,tmp) x=max((x),(tmp))#define smin(x,tmp) x=min((x),(tmp))#define maxx(x1,x2,x3) max(max(x1,x2),x3)#define minn(x1,x2,x3) min(min(x1,x2),x3)const int INF=0x3f3f3f3f;const int maxn = 100005;int dp[maxn];int a[maxn];int n;int main(){#ifndef ONLINE_JUDGE    freopen("sorting.in","r",stdin);    freopen("sorting.out","w",stdout);#endif    scanf("%d",&n);    for(int i=1;i<=n;i++) scanf("%d",a+i);    for(int i=1;i<=n;i++) dp[a[i]] = dp[a[i]-1] + 1;    int ans = *max_element(dp+1,dp+n+1);    printf("%d",n-ans);    return 0;}
0 0
原创粉丝点击