链接:http://codeforces.com/problemset/problem/1437/E
题意:在 a[b[i]]不能修改情况下,求至少需要修改多少数字,使得a数组变成最长上升子序列(严格上升)。
比如:
7 2
1 2 1 1 3 5 1
3 5
a[3]、a[5]数字不能修改,修改后结果可以为:-1 0 1 2 3 5 6
修改了4个数,结果为 4
题解:
- 假如没有”带定值“条件,直接先把原数组 a[i]=a[i]-i 进行变换,然后跑个最长不下降子序列,结果为(n-最长不下降子序列)参考:hdu5256
- 在”带定值“情况下,m=0,直接跑(n-最长不下降子序列)
- 在”带定值“情况下,可以采取分区间处理。a数组中,相邻的两个定值为一个区间,区间为 b[i,i+1],区间左L不能修改,然后跑最长不下降子序列,最后查区间右R(值:a[b[i+1]])在最长不下降子序列(dp临时数组)中的位置pos,当前情况下最长不下降子序列长度为len,当前区间长度为r-l+1,当前区间需要修改的数量为(r-l+1)-pos。
- 注意点:每个区间第一个值不能修改!!
#include <iostream>
#include <vector>
#include <string.h>
#include <algorithm>
using namespace std;
#define INF 0x3f3f3f3f
int n,m;
int a[500005];
int b[500005];
bool check()
{
for(int i=2;i<=m;i++)
{
if(a[b[i]]-a[b[i-1]]<b[i]-b[i-1])
{
cout<<-1<<endl;
return false;
}
}
return true;
}
int solve(int l,int r)
{
int f[r-l+5];
memset(f,0,sizeof(f));
int len = 1;
f[1] = a[l];
for (int i = l+1; i <= r;i++)
if (a[i] >= f[len])
f[++len] = a[i];
else
{
int x = upper_bound(f + 1, f + len + 1, a[i]) - f;
//最长不下降使用 upper_bound,同时if改>=
if(x!=1) // star!!
f[x] = a[i];
}
int pos=upper_bound(f+1,f+1+len,a[r])-f-1;
return (r-l+1)-pos;
}
int main()
{
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
for(int i=1;i<=m;i++)
scanf("%d",&b[i]);
if(check())
{
for(int i=1;i<=n;i++)
a[i]-=i;
a[0]=-INF;a[n+1]=INF;
b[0]=0;b[m+1]=n+1;
int minnum=0;
for(int i=1;i<=m+1;i++)
{
minnum+=solve(b[i-1],b[i]);
}
cout<<minnum<<endl;
}
return 0;
}