You have got a shelf and want to put some books on it.
You are given qq queries of three types:
- L idid — put a book having index idid on the shelf to the left from the leftmost existing book;
- R idid — put a book having index idid on the shelf to the right from the rightmost existing book;
- ? idid — calculate the minimum number of books you need to pop from the left or from the right in such a way that the book with index idid will be leftmost or rightmost.
You can assume that the first book you will put can have any position (it does not matter) and queries of type 33 are always valid (it is guaranteed that the book in each such query is already placed). You can also assume that you don't put the same book on the shelf twice, so idid s don't repeat in queries of first two types.
Your problem is to answer all the queries of type 33 in order they appear in the input.
Note that after answering the query of type 33 all the books remain on the shelf and the relative order of books does not change.
If you are Python programmer, consider using PyPy instead of Python when you submit your code.
Input
The first line of the input contains one integer qq (1≤q≤2⋅1051≤q≤2⋅105 ) — the number of queries.
Then qq lines follow. The ii -th line contains the ii -th query in format as in the problem statement. It is guaranteed that queries are always valid (for query type 33 , it is guaranteed that the book in each such query is already placed, and for other types, it is guaranteed that the book was not placed before).
It is guaranteed that there is at least one query of type 33 in the input.
In each query the constraint 1≤id≤2⋅1051≤id≤2⋅105 is met.
Output
Print answers to queries of the type 33 in order they appear in the input.
一个有趣的思维题。
每当向最左边加入时,L++,右边则R++(第一次不考虑),然后开两个数组r[],和l[](小写的L),x为书本编号,每次放书使先更新L,R。然后对r[x] 和 l[x]赋值,使得r[x] + R 为当前状态下该书本右边的书的数量,l[x] + L为当前状态下该书本左边书的数量,易得出,当放左边时,l[x] = -L, r[x] = L。右边时l[x] = R, r[x] = -R;
每次询问时r[x] + R的值就是编号为x的书右边书的数量,左边同理,下面是对样例的手动模拟
L 1
R = 0, L = 0
r[1] = 0, l[1] = 0
R 2
R = 1, L = 0
r[2] = -1, l[2] = 1;
R 3
R = 2, L = 0
r[2] = -2, l[2] = 0;
? 2
此时r[2] + R = -1 + 2 = 1;
l[2] + L = 1 + 0 = 1;
与实际状况符合
输出1
L 4
R = 2, L = 1
r[4] = 1, l[4] = -1;
? 2
此时r[1] + R = 0 + 2 = 2;
l[1] + L = 0 + 1 = 1;
成立
输出1
L 5
R = 2, L = 2
r[1] = 2, l[1] = -2;
? 1
此时r[1] + R = 0 + 2 = 2;
l[1] + L = 0 + 2 = 2;
成立
输出2
下面上代码
#include <algorithm>
#include <math.h>
#include <string.h>
#include <vector>
#include <stdio.h>
#include <map>
#include<ctype.h>
#define LL long long
using namespace std;
int INF = 1e8;
const int MAX = 2e5 + 50;
int r[MAX];
int l[MAX];
int L, R;
int main(int argc, char const *argv[]){
int n;
scanf("%d", &n);
char c;
int x;
scanf(" %c%d", &c, &x);
n--;
while(n--){
scanf(" %c%d", &c, &x);
if(c == 'L'){
L++;
l[x] = -L;
r[x] = L;
} else if(c == 'R'){
R++;
l[x] = R;
r[x] = -R;
} else{
printf("%d\n", min(L + l[x], R + r[x]));
}
}
return 0;
}