[纪中][线段树]矮人排队

题目大意

给定一个数列。
有两个操作
一,调换队列中下标为 \(x\)\(y\) 的元素的位置;
二,询问一个数列\(D\)\(a, a+1, a+2......b\) 的一种排列方式为该队列的子队列。

解析

一,显然,取这个数列的每个元素所对应的下标的最大值 \(maxt\) 和 最小值 \(mint\)
\(maxt - mint = b - a\) 时为子队列。
二,用线段树来维护这个队列的最大值和最小值。
该线段树的下标为该队列的值(升序),线段树所对应的值是所排元素的下标。

Code

点击查看代码
#include <bits/stdc++.h>
#define N 200005
#define ll long long
using namespace std;

ll n, m;
ll a[N], w[N];
ll maxt, mint;
struct node 
{
	ll l, r, minn, maxx;
}tree[800005];

void hhd (int hd) //维护区间最值
{
	tree[hd].minn = min (tree[hd * 2].minn, tree[hd * 2 + 1].minn);
	tree[hd].maxx = max (tree[hd * 2].maxx, tree[hd * 2 + 1].maxx);
}

void build (int hd, int l, int r) //构造
{
	tree[hd].l = l; tree[hd].r = r; 
	if (l == r)
	{
		tree[hd].minn = tree[hd].maxx = w[l];
		return ;
	}
	ll mid = (l + r) >> 1;
	build (hd * 2, l, mid);
	build (hd * 2 + 1, mid + 1, r);
	hhd (hd);
}

void change (int hd, int x, int y) //区间修改
{
	if (tree[hd].l == tree[hd].r)
	{
		tree[hd].maxx = tree[hd].minn = y;
		return ;
	}
	ll mid = (tree[hd].l + tree[hd].r) >> 1;
	if (x <= mid) change (hd * 2, x, y);
	else change (hd * 2 + 1, x, y);
	hhd (hd);
}

void ask (int hd, int l, int r)//查询
{
//	printf ("hd = %d    l = %d    r = %d     tree[hd].l = %d        tree[hd].r = %d\n", hd, l, r, tree[hd].l, tree[hd].r);
	if (tree[hd].l == l && tree[hd].r == r)
	{
		mint = min (tree[hd].minn, mint);
		maxt = max (tree[hd].maxx, maxt);
		return ;
	}
	ll mid = (tree[hd].l + tree[hd].r) >> 1;
	if (r <= mid) ask (hd * 2, l, r);
	else if (l > mid) ask (hd * 2 + 1, l, r);
	else ask (hd * 2, l, mid), ask (hd * 2 + 1, mid + 1, r);
}

int main ()
{
//	freopen (".in", "r", stdin);
//	freopen (".out", "w", stdout);
	scanf ("%d%d", &n, &m);
	for (int i = 1; i <= n; ++ i)
		scanf ("%d", &a[i]), w[a[i]] = i;
	build (1, 1, n);
	for (int i = 1; i <= m; ++ i)
	{
		int T, x, y;
		scanf ("%d%d%d", &T, &x, &y);
		if (T == 1)
		{
			change (1, a[x], y); change (1, a[y], x);
			swap (a[x], a[y]);
		}	 
		else 
		{
			maxt = 0, mint = 999999999;
			ask (1, x, y);
			if (maxt - mint == y - x) printf ("YES\n");
			else printf ("NO\n"); 
		}
	}
	return 0;
}
posted @ 2022-07-12 14:28  unknown_future  阅读(15)  评论(0编辑  收藏  举报