### 我直接用的小根堆,结果超时了,大佬们帮我看看还能怎么优化?
查看原帖
### 我直接用的小根堆,结果超时了,大佬们帮我看看还能怎么优化?
61399
iawe楼主2020/12/6 19:58
```
#include<cstdio>
#include<algorithm>
#include<cstring>
#define maxn 100000
using namespace std;
int n,lenth=0,heap[maxn],a;
inline void up(int p)
{
    int q=p/2;
    a=heap[p];
    while(q>0&&a<heap[q])
    {
        heap[p]=heap[q];
        p=q;
        q=p/2;
    }
    heap[p]=a;
}
inline void insert(int x)
{
    heap[++lenth]=x;
    up(lenth);
}
inline int search(int p,int x)
{
    if(x==heap[p])
    {
        return p;
    }
    int q=p*2;
    if(x>heap[q])search(q+1,x);
    else search(q,x);
}
inline int forward(int p,int x)
{
    if(x==heap[p])
    {
        if(p==1)return -2147483647;
        else if(p%2==0)return heap[p/2];
        else {
            if(heap[p/2]>heap[p-1])return heap[p/2];
            else return heap[p-1];
        }
    }
    int q=p*2;
    if(q<=lenth)
    {
        if(x>heap[q])forward(q+1,x);
        else forward(q,x);
    }
}
inline int backward(int p,int x)
{
    if(x==heap[p])
    {
        if(p*2>lenth&&p+1>lenth)
        {
          return 2147483647;	
        }
        else 
        {
            if(p*2<lenth)
            {
                if(heap[p*2+1]<heap[p*2])return heap[p*2+1];
                else return heap[p*2];
            }	
            else
            {
                return heap[p+1];
            }
        }
    }
    int q=p*2;
    if(q<=lenth)
    {
        if(x>heap[q])backward(q+1,x);
        else backward(q,x);
    }
}
int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        int s,a;
        scanf("%d%d",&s,&a);
        if(s==1)
        {
            printf("%d\n",search(1,a));
        }
        else if(s==2)
        {
            printf("%d\n",heap[a]);
        }
        else if(s==3)
        {
            printf("%d\n",forward(1,a));
        }
        else if(s==4)
        {
            printf("%d\n",backward(1,a));
        }
        else
        {
            insert(a);
        }
    }
    return 0;
 } 
 ```
2020/12/6 19:58
加载中...