卡牌游戏考场代码
#include<iostream>
#include<cstdio>
#include<cmath>
#include<string>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>
#include<stack>
#include<map>
#define int long long
using namespace std;
inline int read(){
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
const int N=1000010;
struct up{
int x,y;
bool operator < (const up &b) const{
return x<b.x;
}
up(int xx,int yy){
x=xx;
y=yy;
}
};
struct down{
int x,y;
bool operator < (const down &b) const{
return x>b.x;
}
down(int xx,int yy){
x=xx;
y=yy;
}
};
priority_queue<up> q1;
priority_queue<down> q2;
int n,m,a[N],b[N],ans=2e12;
map<int,bool> b1,b2;
void dfs(int x,int y,int p,int q){
if(x==n+1){
ans=min(ans,p-q);
return;
}
if(m!=0)
dfs(x+1,m-1,max(p,b[x]),min(q,b[x]));
dfs(x+1,m,max(p,a[x]),min(q,a[x]));
}
signed main()
{
freopen("card.in","r",stdin);
freopen("card.out","w",stdout);
n=read(),m=read();
for(int i=1;i<=n;i++)
a[i]=read();
for(int i=1;i<=n;i++)
b[i]=read();
if(n<=10){
dfs(1,m,0,2e12);
cout<<ans;
return 0;
}
for(int i=1;i<=n;i++){
up p1=up(a[i],b[i]);
down p2=down(a[i],b[i]);
q1.push(p1);
q2.push(p2);
}
while(m--){
up p1=q1.top();
while(b1[p1.x*p1.y]==1&&b2[p1.x-p1.y]==1){
q1.pop();
p1=q1.top();
}
down p2=q2.top();
while(b1[p2.x*p2.y]==1&&b2[p2.x-p2.y]==1){
q2.pop();
p2=q2.top();
}
q1.pop();
up p3=q1.top();
while(b1[p3.x*p3.y]==1&&b2[p3.x-p3.y]==1){
q1.pop();
p3=q1.top();
}
int pp=max(p3.x,p1.y)-min(p1.y,p2.x);
q1.push(p1);
q2.pop();
down p4=q2.top();
while(b1[p4.x*p4.y]==1&&b2[p4.x-p4.y]==1){
q2.pop();
p4=q2.top();
}
int qq=max(p2.y,p1.x)-min(p4.x,p2.y);
q2.push(p2);
if(pp<=qq){
q1.pop();
up p=up(p1.y,p1.x);
q1.push(p);
down _p=down(p1.y,p1.x);
q2.push(_p);
b1[p1.x*p1.y]=b2[p1.x-p1.y]=1;
b1[p1.x*p1.y]=b2[p1.y-p1.x]=0;
}
else{
q2.pop();
down p=down(p2.y,p2.x);
q2.push(p);
up _p=up(p2.y,p2.x);
q1.push(_p);
b1[p2.x*p2.y]=b2[p2.x-p2.y]=1;
b1[p2.x*p2.y]=b2[p2.y-p2.x]=0;
}
p1=q1.top(),p2=q2.top();
ans=min(ans,p1.x-p2.x);
}
cout<<ans;
return 0;
}