P1198 [JSOI2008]最大數(單調棧,並查集)

傳送門

單調棧的做法顯然,主要是這道題爲什麼可以用並查集來代替二分查找

在將一個數插入單調隊列時,我們可以將被刪除的數的父親標記爲插入的數,在查找時只需要找到查找的數的根,根上的數值即爲答案。

證明?不會證qwq

複雜度O(n)O(n)

code:

#include<cstdio>
using namespace std;
const int Maxn=200010;
struct node
{
    long long x;
    int y;
}a[Maxn];
int m,tot,cnt,f[Maxn];
long long d,t,x,num[Maxn];
char ch[3];
int find(int x)
{
    if(x!=f[x])f[x]=find(f[x]);
    return f[x];
}
int main()
{
    scanf("%lld%lld",&m,&d);
    for(int i=1;i<=m;i++)
    {
        getchar();
        scanf("%s",ch);
        scanf("%lld",&x);
        if(ch[0]=='A')
        {
            x+=t;
            x%=d;
            tot++;
            num[tot]=x;
            f[tot]=tot;
            while(x>a[cnt].x&&cnt)
            {
                f[a[cnt].y]=tot;
                cnt--;
            }
            a[++cnt].x=x;
            a[cnt].y=tot;
        }
        else
        {
            x=tot-x+1;
            int y=find(x);
            t=num[y];
            printf("%lld\n",t);
        }
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章