codeforces 605 A. Sorting Railway Cars (dp)
题意:给出一个n个数的排列,每次可以把一个数放到最前面或者最后面的位置,问至少要进行多少次操作才能使得数列升序。
思路:考虑不被移动的那些数,当把所有一定的数去掉以后,这些剩下的数一定是一段数值连续,位置递增的数。如果想要移动的数最少,俺么这串递增的数就尽可能长。
dp[a[i]] = dp[a[i]-1] + 1
那么ans = n - max{dp[i]}
另外:对于要移动的数,我们可以按照一定顺序(放在前面的数按照递减顺序,放在最长序列后面的数按照递增顺序)移动,可以保证每个数只需要移动一次。
1/* ***********************************************
2Author :111qqz
3Created Time :2016年10月04日 星期二 20时10分00秒
4File Name :code/cf/problem/605A.cpp
5************************************************ */
6
7#include <cstdio>
8#include <cstring>
9#include <iostream>
10#include <algorithm>
11#include <vector>
12#include <queue>
13#include <set>
14#include <deque>
15#include <map>
16#include <string>
17#include <cmath>
18#include <cstdlib>
19#include <bitset>
20#define fst first
21#define sec second
22#define lson l,m,rt<<1
23#define rson m+1,r,rt<<1|1
24#define ms(a,x) memset(a,x,sizeof(a))
25typedef long long LL;
26#define pi pair < int ,int >
27#define MP make_pair
28
29using namespace std;
30const double eps = 1E-8;
31const int dx4[4]={1,0,0,-1};
32const int dy4[4]={0,-1,1,0};
33const int inf = 0x3f3f3f3f;
34const int N=1E5+7;
35int n;
36int a[N];
37int dp[N];
38int main()
39{
40 #ifndef ONLINE_JUDGE
41 freopen("code/in.txt","r",stdin);
42 #endif
43
44 cin>>n;
45 for ( int i = 1 ; i <= n ; i++) cin>>a[i];
46 ms(dp,0);
47 int mx = 0 ;
48 for ( int i = 1 ; i <= n ; i++)
49 {
50 dp[a[i]] = dp[a[i]-1] + 1;
51 mx = max(dp[a[i]],mx);
52 }
53 cout<<n-mx<<endl;
54
55 #ifndef ONLINE_JUDGE
56 fclose(stdin);
57 #endif
58 return 0;
59}