51nod-1294 修改数组

题目来源:  HackerRank
基准时间限制:1 秒 空间限制:131072 KB 分值: 160  难度:6级算法题
 收藏
 关注
给出一个整数数组A,你可以将任何一个数修改为任意一个正整数,最终使得整个数组是严格递增的且均为正整数。问最少需要修改几个数?
Input
第1行:一个数N表示序列的长度(1 <= N <= 100000)。
第2 - N + 1行:每行1个数,对应数组元素。(0 <= A[i] <= 10^9)
Output
输出最少需要修改几个数使得整个数组是严格递增的。
Input示例
5
1
2
2
3
4
Output示例
3

题解:对于a[i] - i小于0的肯定不能取,因为要求都是正整数,且严格递增,所以第i位的最小值是i!

对于a[i] - i大于0的部分求最长非严格递增子序列,答案就是n - 子序列长度。

为什么?因为对于原数组的ai和aj(i > j),必须满足ai - aj >= i - j, 即ai - i >= aj - j.故我们对于ai - i 求非严格递增子序列既是不需要改变的部分!

AC代码

#include <stdio.h>
#include <iostream>
#include <string>
#include <queue>
#include <map>
#include <vector>
#include <algorithm>
#include <string.h>
#include <cmath>
 
using namespace std;

const int maxn = 1e5 + 10;
int a[maxn], p[maxn];

int main(){
	int n, num, ans, now;
	scanf("%d", &n);
	num = ans = now = 0;
	for(int i = 1; i <= n; i++){
		scanf("%d", &a[i]);
		if(a[i] - i >= 0)
			a[++num] = a[i] - i;
		else
			ans++;
	}
	p[now] = -1;
	for(int i = 1; i <= num; i++){
		if(p[now] <= a[i])
			p[++now] = a[i];
		else{
			int l = 1, r = now;
			while(l <= r){
				int m = (l + r) >> 1;
				if(p[m] > a[i])
					r = m - 1;
				else
					l = m + 1;
			}
			p[l] = a[i];
		}
	}
	cout << now << endl;
	printf("%d\n", ans + num - now);
	return 0;
} 


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值