P10237 [yLCPC2024] E. Latent Kindom 题解

分析

一眼了非最优解。

考虑二分答案。对于二分出来的中位数 x,到 aiaj 里边又去二分。得到两个序列中不超过 x 的数的数量。若这个数量 cntleni+lenj2,则 x 可能成为中位数,然后继续二分即可。

把序列离散化,复杂度为 O(nlog2n),然后因为 3s 就过了。

代码

#include<bits/stdc++.h>
using namespace std;
#define int long long
#define re register
#define il inline
#define pii pair<int,int>
#define x first
#define y second
#define gc getchar()
#define rd read()
#define debug() puts("------------")

namespace yzqwq{
	il int read(){
		int x=0,f=1;char ch=gc;
		while(ch<'0'||ch>'9'){if(ch=='-') f=-1;ch=gc;}
		while(ch>='0'&&ch<='9') x=(x<<1)+(x<<3)+(ch^48),ch=gc;
		return x*f;
	}
	il int qmi(int a,int b,int p){
		int ans=1;
		while(b){
			if(b&1) ans=ans*a%p;
			a=a*a%p,b>>=1;
		}
		return ans;
	}
	il auto max(auto a,auto b){return (a>b?a:b);}
	il auto min(auto a,auto b){return (a<b?a:b);}
	il int gcd(int a,int b){
		if(!b) return a;
		return gcd(b,a%b);
	}
	il int lcm(int a,int b){
		return a/gcd(a,b)*b;
	}
	il void exgcd(int a,int b,int &x,int &y){
		if(!b) return x=1,y=0,void(0);
		exgcd(b,a%b,x,y);
		int t=x;
		x=y,y=t-a/b*x;
		return ;
	}
	mt19937 rnd(time(0));
}
using namespace yzqwq;

const int N=5e6+10;
int n,q,b[N],idx;
int len[N];
vector<int> a[N];

il bool check(int x,int y,int z){
	int l1=0,r1=len[x]-1,w1=-1;
	while(l1<=r1){
		int mid=l1+r1>>1;
		if(a[x][mid]<=z) w1=mid,l1=mid+1;
		else r1=mid-1;
	}
	int l2=0,r2=len[y]-1,w2=-1;
	while(l2<=r2){
		int mid=l2+r2>>1;
		if(a[y][mid]<=z) w2=mid,l2=mid+1;
		else r2=mid-1;
	}
	int Len=len[x]+len[y];
	Len=(Len-1)/2+1;
	int s1=0,s2=0;
	s1=w1-0+1;
	s2=w2-0+1;
	return s1+s2>=Len;
}

il void solve(){
	n=rd,q=rd;idx=0;
	for(re int i=1;i<=n;++i){
		len[i]=rd;
		a[i].clear();
		for(re int j=1;j<=len[i];++j)
			b[++idx]=rd,a[i].push_back(b[idx]);
		sort(a[i].begin(),a[i].end());
	}
	sort(b+1,b+idx+1),idx=unique(b+1,b+idx+1)-(b+1);
	for(re int i=1;i<=n;++i){
		for(re int j=0;j<len[i];++j){
			a[i][j]=lower_bound(b+1,b+idx+1,a[i][j])-b;
		}
	}
	while(q--){
		int x=rd,y=rd;
		int l=1,r=idx+1,ans=-1;
		while(l<=r){
			int mid=l+r>>1;
			if(check(x,y,mid)) ans=mid,r=mid-1;
			else l=mid+1;
		}
		printf("%lld\n",b[ans]);
	}
	return ;
}

signed main(){
//	freopen(".in","r",stdin);
//	freopen(".out","w",stdout);
	int t=rd;while(t--)
	solve();
	return 0;
}

posted @   harmis_yz  阅读(36)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示