標籤:51nod csdn 中國電信
題目意思:51nod1294
http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1294
給出一個整數數組A,你可以將任何一個數修改為任意一個正整數,最終使得整個數組是嚴格遞增的且均為正整數。問最少需要修改幾個數?
Input
第1行:一個數N表示序列的長度(1 <= N <= 100000)。第2 - N + 1行:每行1個數,對應數組元素。(0 <= A[i] <= 10^9)
Output
輸出最少需要修改幾個數使得整個數組是嚴格遞增的。
Input 樣本
512234
Output 樣本
3
題目分析:
對於此類問題,特點在原位置的排序,我們的處理思路就是,首先每一個數減去其所在的位置,再對其進行使用LIS,但需要注意題目中要求的是正整數,所以我們必須對大於等於0的值進行LIS,修改的個數就是n-最長的LIS。
AC代碼(java/c++):
C++:
#include<iostream>#include<algorithm>#include<cstring>#include<cstdio>#include<vector>#include<iterator>#define MAX 100005using namespace std;int a[MAX],b[MAX];int main(){ int n; while(scanf("%d",&n)!=EOF){ int cnt=0; vector<int> v; vector<int>::iterator it; for(int i=0;i<n;i++){ scanf("%d",&a[i]); a[i]=a[i]-(i+1);//每一個數減去其所在位置的序號 if(a[i]>=0) b[cnt++]=a[i]; } if(cnt==0){ cout<<n<<endl; continue; } v.push_back(b[0]); for(int i=1;i<cnt;i++){ if(b[i]>=*(v.end()-1)){ v.push_back(b[i]); } else{ it=upper_bound(v.begin(), v.end(), b[i]); *(it)=b[i]; } } //printf("%d\n",v.size()); printf("%d\n",n-v.size()); } return 0;}
java代碼:
import java.lang.reflect.Array;import java.util.Arrays;import java.util.Scanner;import javax.naming.BinaryRefAddr;import javax.xml.soap.SAAJResult;public class XUIGAI_ARRAY {static int BinarySearch(int s[],int x,int low,int high){while(low<=high){int middle=(high+low)/2; if(x<s[middle])high=middle-1; else if(x>s[middle])low=middle+1; else return middle;}return high+1;}public static void main(String[] args) {int a[]=new int[1000005];int b[]=new int[1000005];int c[]=new int[1000005];int n,cnt;Scanner sc=new Scanner(System.in);while(sc.hasNext()){n=sc.nextInt();cnt=0;for(int i=0;i<n;i++){a[i]=sc.nextInt();a[i]=a[i]-(i+1);if(a[i]>=0) b[cnt++]=a[i];}if(cnt==0){System.out.println(n);continue;}int len=1,pos;c[len-1]=b[0];for(int i=1;i<cnt;i++){//System.out.println(b[i]);if(b[i]>=c[len-1]){c[len++]=b[i];}else{pos=BinarySearch(c, b[i], 0, len-1);//System.out.println(pos);if(pos>=0&&pos<=len-1) for(int j=pos;j<=len;j++){if(c[j]>b[i]){pos=j; break;}}c[pos]=b[i];}}System.out.println(n-len);}}}
CSDN 中國電信翼支付2014編程大賽複賽 修改數列(LIS)