The Smart Beaver has recently designed and built an innovative nanotechnologic all-purpose beaver mass shaving machine, "Beavershave 5000". Beavershave 5000 can shave beavers by families! How does it work? Very easily!
There are
n beavers, each of them has a unique id from 1 to
n. Consider a permutation
a1,a2,...,an of
n these beavers. Beavershave 5000 needs one session to shave beavers with ids from
x to
y (inclusive) if and only if there are such indices
i1<i2<...<ik, that
ai1=x,
ai2=x+1, ...,
aik-1=y-1,
aik=y. And that is really convenient. For example, it needs one session to shave a permutation of beavers
1,2,3,...,n.
If we can't shave beavers from
x to
y in one session, then we can split these beavers into groups
[x,p1],
[p1+1,p2], ...,
[pm+1,y] (x≤p1<p2<...<pm<y), in such a way that the machine can shave beavers in each group in one session. But then Beavershave 5000 needs
m+1 working sessions to shave beavers from
x to
y.
All beavers are restless and they keep trying to swap. So if we consider the problem more formally, we can consider queries of two types:
-
what is the minimum number of sessions that Beavershave 5000 needs to shave beavers with ids from x to y, inclusive?
-
two beavers on positions x and y (the beavers ax and ay) swapped.
You can assume that any beaver can be shaved any number of times.