今天省赛被虐了,发段以前写的代码纪念下先:
题目如下:
Problem Description
At the beginning of learning programming, your teacher must teach you how to sort an array via
insertion sort. Then, let’s sort an array as ascending order with a operation described below:
Operation: As one time, you can select one element and insert it to the position whatever you
want.
Could you tell me the minimum number of operations to finish sorting.
insertion sort. Then, let’s sort an array as ascending order with a operation described below:
Operation: As one time, you can select one element and insert it to the position whatever you
want.
Could you tell me the minimum number of operations to finish sorting.
Input
The input consists of T test cases.
The number of test cases T is given in the first line of the input.
Each test case begins with a line containing an integer N , 1 ≤ N ≤ 500, 000, representing the
number of integers in the array. Each of the following N integers that belong to the array.
The number of test cases T is given in the first line of the input.
Each test case begins with a line containing an integer N , 1 ≤ N ≤ 500, 000, representing the
number of integers in the array. Each of the following N integers that belong to the array.
Output
The output should contain the minimum number of operations to finish sorting, one per line.
Sample Input
2 3 1 2 3 3 1 3 2
Sample Output
0 1
#include <stdio.h>
#define maxlen 50000+10
int dp[maxlen];
int main()
{
int n,T,temp,max;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
scanf("%d",&temp);
max=1;dp[1]=temp;
for(int i=2;i<=n;i++)
{
scanf("%d",&temp);
int j;
for(j=max;j>=1;j--)
{
if(dp[j]<=temp)break;//break在这里很关键,不可缺少 用来保证其最优子结构性质
//dp[i]用来保存当最长子序列为i时该
//子序列的最后一个元素的大小。
}
dp[j+1]=temp; //因为是从后往前搜索,当遇到第一个
//之前计算出来的最长子序列必定为
//该状态下之前当中最长,此时即可停止搜索
if(j==max)max++; //当然,只有当搜索出上次决策的最长跟总的
//最长相等时(因为不可能比最长的还大)
//当前规划后才可能让max变大
}
printf("%d\n",n-max);
}
return 0;
}