两个有序序列的中位数(二分)

#include<iostream>
using namespace std;
int a[100000],b[100000];
int search(int,int,int,int);
int main()
{
    int n,i;
    while(cin>>n)
    {
        for(i=0;i<n;i++)
            cin>>a[i];
        for(i=0;i<n;i++)
            cin>>b[i];
        cout<<search(0,n-1,0,n-1)<<'\n';
    }
    return 0;
}
int search(int l,int r,int x,int y)
{
    int m=(l+r)>>1,z=(x+y+1)>>1;
    if(l==r&&x!=y)
        if(a[l]>b[y])return b[y];
        else return a[l];
    if(l!=r&&x==y)
        if(a[r]<b[x])return a[r];
        else return b[x];
    if(l==r&&x==y)
        if(a[l]>b[x])return b[x];
        else return a[l];
    else
    {
        if(l==r-1&&x==y-1)
        {
            m=(l+r)>>1;
            z=(x+y)>>1;
        }
        if(a[m]==b[z])return a[m];
        else if(a[m]>b[z])return search(l,m,z,y);
        else return search(m,r,x,z);
    }
}

猜你喜欢

转载自www.cnblogs.com/MTstory/p/11574948.html