完了,这场先WA一发 A,再WA B,然后发现问题后又WA一发A。。。心态爆炸,不然这题早过了,而且也能写完I了。
Last time, the king of the country Qi lost to Tian Ji in a horse race as Tian using a little trick. Today, the king invites Tian to play another horse race. The king and Tian both have n horses, and no two horses have the same speed. They will play n rounds in this match. The horses on each side must appear in descending order of speed, and each of the horses must be used in one round. The horse with a faster speed will win in a single round. Since Tian's horses are not so nice as the king's, the king allows Tian to exchange some horses with him.
If Tian can exchange at most k horses with the king, what is the maximum number of rounds that Tian can win?
A数组表示齐王的马,B数组表示田忌的马
我们先处理出nxt[i]表示a[i]插入到b数组中的位置,pre[i]表示b[i]插到a数组中的位置
每次交换就是把a最大的拿出来插入b数组,b最小的拿出来插入a数组。
那么 l=nxt[i] ,r=pre[n-i+1]-i-i ,为b数组中还没有全部能赢的区间,从[1,l-1] [r+1,n]是全部能赢的
我们处理出 f[i] ,表示b数组中的每个bi 向右移动多少才能比比对应的A大
每次是a数组的pre[n-i+1]到1的位置向左移动,b数组从nxt[i]到n向右移动,相当于a相对位移了2
那么对于中间的区间我们把f[i]当权值建权值树状数组,每次交换移动2,num+=2,那么f[i]<=num的都可以赢了
然后对于新增的必赢的区间,我们去树状数组中减去
#include<bits/stdc++.h>
#define maxl 100010
using namespace std;
int n,m,mxk;
int a[maxl],b[maxl],f[maxl],ans[maxl];
int bit[maxl];
int nxt[maxl],pre[maxl];
inline void add(int i,int x)
{
while(i<=n)
{
bit[i]+=x;
i+=i&-i;
}
}
inline int sum(int i)
{
int ret=0;
while(i)
{
ret+=bit[i];
i-=i&-i;
}
return ret;
}
inline void prework()
{
for(int i=1;i<=n;i++)
scanf("%d",&a[i]),bit[i]=0;
for(int i=1;i<=n;i++)
scanf("%d",&b[i]);
mxk=0;
for(int i=1;i<=n;i++)
{
if(a[i]<=b[n-i+1])
{
mxk=i-1;
break;
}
else
mxk=i;
}
int id=1;
for(int i=1;i<=n;i++)
{
while(a[id]>=b[i] && id<=n)
id++;
if(id>n)
f[i]=maxl-1;
else
{
if(id>=i)
f[i]=id-i+1;
else
f[i]=1;
add(f[i],1);
}
}
id=1;
for(int i=1;i<=mxk;i++)
{
while(b[id]>=a[i] && id<=n)
id++;
nxt[i]=id;
}
id=n;
for(int i=1;i<=mxk;i++)
{
while(a[i]<=b[n-i+1] && id>0)
id--;
pre[n-i+1]=id;
}
}
inline void mainwork()
{
ans[0]=sum(1);int l=1,r=n,lastl,lastr,num=1;
for(int i=1;i<=mxk;i++)
{
lastl=l;lastr=r;
l=nxt[i];r=pre[n-i+1]-i-i;
if(l>r)
{
mxk=i-1;
return;
}
for(int j=lastl;j<l;j++)
{
if(f[j]>0 && f[j]<maxl-1)
add(f[j],-1);
}
for(int j=lastr;j>r;j--)
{
if(f[j]>=0 && f[j]<maxl-1)
add(f[j],-1);
}
num+=2;
ans[i]=n-(r-l+1)+sum(num);
}
}
inline void print()
{
int k;
for(int i=1;i<=m;i++)
{
scanf("%d",&k);
if(k>mxk)
printf("%d\n",n);
else
printf("%d\n",ans[k]);
}
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
prework();
mainwork();
print();
}
return 0;
}
/**********************************************************************
Problem: 2000
User: liufengwei
Language: C++
Result: AC
Time:532 ms
Memory:4756 kb
**********************************************************************/