RMQ with Shifts
In the traditional RMQ (Range Minimum Query) problem, we have a static array A. Then for each query (L, R) (L<=R), we report the minimum value among A[L], A[L+1], …, A[R]. Note that the indices start from 1, i.e. the left-most element is A[1].
In this problem, the array A is no longer static: we need to support another operation shift(i1, i2, i3, …, ik) (i1 < i2 < …< ik, k>1): we do a left “circular shift” of A[i1], A[i2], …, A[ik].
For example, if A={6, 2, 4, 8, 5, 1, 4}, then shift(2, 4, 5, 7) yields {6, 8, 4, 5, 4, 1, 2}. After that, shift(1,2) yields {8, 6, 4, 5, 4, 1, 2}.
Input
There will be only one test case, beginning with two integers n, q (1<=n<=100,000, 1<=q<=120,000), the number of integers in array A, and the number of operations. The next line contains n positive integers not greater than 100,000, the initial elements in array A. Each of the next q lines contains an operation. Each operation is formatted as a string having no more than 30 characters, with no space characters inside. All operations are guaranteed to be valid. Warning: The dataset is large, better to use faster I/O methods.
Output
For each query, print the minimum value (rather than index) in the requested range.
Sample Input
7 5
6 2 4 8 5 1 4
query(3,7)
shift(2,4,5,7)
query(1,4)
shift(1,2)
query(2,2)
Sample Output
1
4
6
题意:就是对一个区间进行查询和给出个个位置的对调关系,第2个和第4对调,再第4和第5个对调。。。。然后面对query输出结果;
思路:很明显的线段树单点更新问题,输入数据有点麻烦,可以参考代码,再者就是时间复杂度的问题,要找规律不能直接模拟,每一次其实只要进行一次更新就行了,最后将最后一个更新为第一个就行了。
易错点:
1. rt<<1+1中+1的优先级居然高于位移运算符<<,应该是(rt<<1)+1。
2. 就是不能直接模拟,要每次只更新一次。
3. 是一个入门的线段树经典题。
AC代码:
#include <cstdio>
#include <iostream>
#include<algorithm>
using namespace std;
int sum[400000],a[100000];
int con=1;
void build(int l,int r,int rt)
{
if(l==r)
{
cin>>sum[rt];
a[con++]=sum[rt];
return;
}
int mid=(l+r)>>1;
build(l,mid,rt<<1);
build(mid+1,r,(rt<<1)+1);
sum[rt]=min(sum[rt<<1],sum[(rt<<1)+1]);
}
int qmin(int ql,int qr,int l,int r,int rt)
{
if(ql<=l&&qr>=r)
{
return sum[rt];
}
if(l==2&&r==3)
return -1;
int mid=(l+r)>>1;
if(qr<=mid)
{
return qmin(ql,qr,l,mid,rt<<1);
}
else
{
if(ql>mid)
{
return qmin(ql,qr,mid+1,r,(rt<<1)+1);
}
else
{
return min(qmin(ql,qr,l,mid,rt<<1),qmin(ql,qr,mid+1,r,(rt<<1)+1));
}
}
}
void update(int p,int q,int l,int r,int rt)
{
if(l==p&&r==p)
{
sum[rt]=q;
return;
}
int m=(l+r)>>1;
if(p<=m)
update(p,q,l,m,rt<<1);
else
update(p,q,m+1,r,(rt<<1)+1);
sum[rt]=min(sum[rt<<1],sum[(rt<<1)+1]);
}
int main ()
{
int n,q;
while(cin>>n>>q)
{
con=1;
build(1,n,1);
int x,y;
char s[10];
while (q--)
{
scanf("%6s",s);
if (s[0]=='q')
{
scanf("%d,%d)",&x,&y);
printf("%d\n",qmin(x,y,1,n,1));
}
if (s[0]=='s')
{
char c;
int cnt=0,prex,prey,first;
while (~scanf("%d%c",&x,&c))
{
if(cnt==0)
{
cnt++;
first=a[x];
prex=x;
continue;
}
update(prex,a[x],1,n,1);
swap(a[prex],a[x]);
prex=x;
if (c!=',') break;
}
update(x,first,1,n,1);
}
}
}
return 0;
}