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


猜你喜欢

转载自blog.csdn.net/qq_37064135/article/details/80490196