最长子序列一种解法

今天省赛被虐了,发段以前写的代码纪念下先:

题目如下:

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.

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.

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值