您的位置:首页 > 大数据 > 人工智能

CF#335 Sorting Railway Cars

2015-12-21 09:25 519 查看
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的n个数,各不相同,每一步可以将任意一个取出,放在开头或者结尾,问把这个序列变回1-n,要多少步。

分析:显然,每个数最多取出一次,否则没有意义。

这样的话,我们可以将取出和放下(放在开头或者结尾)分开考虑。

取出之后剩下的东西一定是一个连续的上升子序列,当这个序列最长时,答案最优。

因为可以调整取出顺序,放回当然按大小顺序放回(即按大小顺序取出)就好。

注意一定是连续的上升子序列,这里的连续指的是数值上的连续。

/**
Create By yzx - stupidboy
*/
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <deque>
#include <vector>
#include <queue>
#include <iostream>
#include <algorithm>
#include <map>
#include <set>
#include <ctime>
#include <iomanip>
using namespace std;
typedef long long LL;
typedef double DB;
#define MIT (2147483647)
#define INF (1000000001)
#define MLL (1000000000000000001LL)
#define sz(x) ((int) (x).size())
#define clr(x, y) memset(x, y, sizeof(x))
#define puf push_front
#define pub push_back
#define pof pop_front
#define pob pop_back
#define mk make_pair

inline int Getint()
{
int Ret = 0;
char Ch = ' ';
bool Flag = 0;
while(!(Ch >= '0' && Ch <= '9'))
{
if(Ch == '-') Flag ^= 1;
Ch = getchar();
}
while(Ch >= '0' && Ch <= '9')
{
Ret = Ret * 10 + Ch - '0';
Ch = getchar();
}
return Flag ? -Ret : Ret;
}

const int N = 100010;
int n, arr
;
int cnt
;

inline void Input()
{
scanf("%d", &n);
for(int i = 1; i <= n; i++) scanf("%d", &arr[i]);
}

inline void Solve()
{
for(int i = 1; i <= n; i++)
cnt[arr[i]] = cnt[arr[i] - 1] + 1;
int ans = 0;
for(int i = 1; i <= n; i++)
ans = max(ans, cnt[i]);
printf("%d\n", n - ans);
}

int main()
{
freopen("a.in", "r", stdin);
Input();
Solve();
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: