const double eps = 1e-6; const LL mod=1e9+7; const LL INF=(LL)1e18; using namespace std; LL gcd(LL a,LL b){return b==0?a:gcd(b,a%b);} LL qpow(LL x,LL y){LL re=1,base=x%mod;while(y){if(y&1)re=(re*base)%mod;base=(base*base)%mod;y>>=1;}return re;} struct node{ int m,l,r; node(int m,int l,int r):m(m),l(l),r(r){} bool operator < (const node& x) const{ return m>x.m; } }; int dp[2][maxn][36]; int pos[maxn]; int a[2][maxn]; void makermq(int n,int f){ for(int i=0;i<n;i++) dp[f][i][0]=a[f][i]; for(int j=1;(1<<j)<=n;j++) for(int i=0;i+(1<<j)-1<n;i++) dp[f][i][j]=min(dp[f][i][j-1],dp[f][i+(1<<(j-1))][j-1]); } int rmq(int s,int v,int f){ int k=(int)(log((v-s+1)*1.0)/log(2.0)); return min(dp[f][s][k],dp[f][v-(1<<k)+1][k]); } int main(){ // freopen("input.txt","r",stdin); // freopen("ouput.txt","w",sdout); ios::sync_with_stdio(false); cin.tie(0),cout.tie(0); int n; cin>>n; mm(pos,0); for(int i=0;i<n;i++){ int x; cin>>x; pos[x]=i; a[i&1][i]=x; a[(i&1)^1][i]=inf; } makermq(n,0),makermq(n,1); int x1=rmq(0,n-1,0); priority_queue<node>q; q.push(node(x1,0,n-1)); while(!q.empty()){ node x=q.top(); q.pop(); int v1=x.m; int v2=rmq(pos[v1]+1,x.r,(pos[v1]&1)^1); cout<<v1<<" "<<v2<<" "; int pos1=pos[v1],pos2=pos[v2]; if(pos1!=x.l) q.push(node(rmq(x.l,pos1-1,x.l&1),x.l,pos1-1)); if(pos1+1!=pos2) q.push(node(rmq(pos1+1,pos2-1,(pos1+1)&1),pos1+1,pos2-1)); if(pos2!=x.r) q.push(node(rmq(pos2+1,x.r,(pos2+1)&1),pos2+1,x.r)); } cout<<endl; return 0; }
|