bzoj4358 premu

题目链接

莫队算法

没有用线段树,而是看了showson的并查集%%%

 1 #include<algorithm>
 2 #include<iostream>
 3 #include<cstdlib>
 4 #include<cstring>
 5 #include<cstdio>
 6 #include<string>
 7 #include<cmath>
 8 #include<ctime>
 9 #include<queue>
10 #include<stack>
11 #include<map>
12 #include<set>
13 #define rre(i,r,l) for(int i=(r);i>=(l);i--)
14 #define re(i,l,r) for(int i=(l);i<=(r);i++)
15 #define Clear(a,b) memset(a,b,sizeof(a))
16 #define inout(x) printf("%d",(x))
17 #define douin(x) scanf("%lf",&x)
18 #define strin(x) scanf("%s",(x))
19 #define LLin(x) scanf("%lld",&x)
20 #define op operator
21 #define CSC main
22 typedef unsigned long long ULL;
23 typedef const int cint;
24 typedef long long LL;
25 using namespace std;
26 void inin(int &ret)
27 {
28     ret=0;int f=0;char ch=getchar();
29     while(ch<'0'||ch>'9'){if(ch=='-')f=1;ch=getchar();}
30     while(ch>='0'&&ch<='9')ret*=10,ret+=ch-'0',ch=getchar();
31     ret=f?-ret:ret;
32 }
33 int n,m,a[50050],wei[50050],temp;
34 int fa[50050],s[50050],bo[50050],pos[50050],sta[50050],top,ANS[50050];
35 struct que
36 {
37     int l,r,id;
38     void in(int i){inin(l),inin(r),id=i;}
39     bool op < (const que &rhs)const {return wei[l]==wei[rhs.l]?r<rhs.r:l<rhs.l;}
40 }q[50050];
41 int find(int x){return x==fa[x]?x:fa[x]=find(fa[x]);}
42 void merge(int x,int y)
43 {
44     x=find(x),y=find(y);
45     if(x==y)return ;
46     s[x]+=s[y];
47     temp=max(temp,s[x]);
48     fa[y]=x;
49 }
50 void init()
51 {
52     re(i,1,n)fa[i]=i,s[i]=0;
53     temp=1;    
54 }
55 void add(int x)
56 {
57     bo[x]=1;
58     s[x]=1;
59     if(bo[x-1])merge(x-1,x);
60     if(bo[x+1])merge(x,x+1);
61 }
62 int main()
63 {
64     inin(n);inin(m);
65     int nn=sqrt(n);
66     re(i,1,n)inin(a[i]),wei[i]=(i-1)/nn+1,pos[a[i]]=i;
67     re(i,1,m)q[i].in(i);
68     sort(q+1,q+m+1);
69     int r=0;
70     re(i,1,m)
71     {
72         if(i==1||wei[q[i].l]!=wei[q[i-1].l])
73         {
74             Clear(bo,0);Clear(s,0);
75             init(),top=0;
76             int head=(q[i].l-1)/nn*nn+1;
77             r=min(head+nn-1,n);
78             re(j,head,r)sta[++top]=a[j];
79             sort(sta+1,sta+top+1);
80         }
81         while(r<q[i].r)add(a[++r]);
82         int ans=temp,nl=1,nr=0;
83         re(j,1,top)
84         {
85             int c=sta[j];
86             if(pos[c]<q[i].l||pos[c]>q[i].r)continue;
87             if(c==nr+1)nr+=s[find(c+1)]+1;
88             else 
89             {
90                 ans=max(ans,nr-nl+1);
91                 nl=c-s[find(c-1)];
92                 nr=c+s[find(c+1)];
93             }
94         }
95         ANS[q[i].id]=max(ans,nr-nl+1);
96     }
97     re(i,1,m)printf("%d\n",ANS[i]);
98      return 0;
99 }

 

你可能感兴趣的:(bzoj4358 premu)