分塊=-=優雅的暴力=-=中位數模版

whrwlx發表於2024-05-03
#include<bits/stdc++.h>
//#define int long long
#define ll long long
#define fd(i,a,b) for(register int i=a;i<=b;i=-~i)
#define bd(i,a,b) for(register int i=a;i>=b;i=~-i)
using namespace std;

const int N=1e5+509,M=509,MOD=10007;
int n,siz,id;
int bel[N],a[N];
int sum[M],add[M],L[M],R[M],cnt[70005],val[N],f[M][M];
unordered_map<int,int> mp;
vector<int> ve[N];

inline int read()
{
    int num=0; bool flag=1; char c=getchar();
    while(!isdigit(c)){if(c=='-') flag=0;c=getchar();}
	while(isdigit(c)){num=(num<<1)+(num<<3)+(c-'0');c=getchar();}
    return flag?num:-num;
}

inline void write(int x)
{
    if(x<0) putchar('-'),x=-x;
    if(x>9) write(x/10);
	putchar((x%10)^48);
}

namespace FJ
{
	
	void build(int len)
	{
	    siz=sqrt(len);
		fd(i,1,siz)
		{
			L[i]=(i-1)*siz+1;
			R[i]=i*siz;
		}
		if(R[siz]<len)
		{
	        ++siz;
	        L[siz]=R[siz-1]+1;
	        R[siz]=n;
	    }
	    fd(i,1,siz)
		{
	        fd(j,L[i],R[i])
			{
	            bel[j]=i;
	        }
	    }
	    fd(i,1,siz)
	    {
	    	memset(cnt,0,sizeof(cnt));
		    int mx=0,ans=0;
		    fd(j,L[i],n)
		    {       
		        cnt[a[j]]=-~cnt[a[j]];
		        if(cnt[a[j]]>mx||((cnt[a[j]]==mx&&val[a[j]]<val[ans])))
		            ans=a[j],mx=cnt[a[j]];
		        f[i][bel[j]]=ans;
		    }
		}
	}
	
	int query(int l,int r,int x)
	{
		int t=upper_bound(ve[x].begin(),ve[x].end(),r)-lower_bound(ve[x].begin(),ve[x].end(),l);
    	return t;
	}
	
	int ask(int l,int r)
	{
	    int p=bel[l],q=bel[r];
	    int res=0,mx=0;
	    res=f[bel[l]+1][bel[r]-1];
	    mx=query(l,r,res);
	    if(p==q)
	    {
	    	fd(i,l,r)
	    	{
	    		int t=query(l,r,a[i]);
        		if(t>mx||(t==mx&&val[a[i]]<val[res])) res=a[i],mx=t;
			}
			return res;
		}
		fd(i,l,R[p])
		{
			int t=query(l,r,a[i]);
        	if(t>mx||(t==mx&&val[a[i]]<val[res])) res=a[i],mx=t;
		}
		fd(i,L[q],r)
		{
			int t=query(l,r,a[i]);
        	if(t>mx||((t==mx&&val[a[i]]<val[res]))) res=a[i],mx=t;
		}
		return res;
	}
	
}

signed main()
{
// 	freopen("A.in","r",stdin);
//	freopen("A.out","w",stdout);
//	#ifdef FJ
//	ios::sync_with_stdio(0);
//	cin.tie(0); cout.tie(0);
//	#endif
	n=read();
	fd(i,1,n)
	{
		a[i]=read();
		if(!mp[a[i]])
        {
            mp[a[i]]=++id;
            val[id]=a[i];
        }
        a[i]=mp[a[i]];
        ve[a[i]].push_back(i);
	}
	FJ::build(n);
	fd(i,1,n)
	{
		int opt,a,b,c;
		a=read();b=read();//c=read();
		write(val[FJ::ask(a,b)]),puts("");
	}
	return 0;
}

相關文章