题目:http://codeforces.com/contest/1066/problem/C
大意是在一个书架上放书,一共q次操作,每次操作可以把书放在最左边或最右边,要么询问把第id本书的右边的所有书或左边的所有书都清空的最小清空数量。
用一个数组表示书架位信息,l和r表示到现在最左和最右的位置。
#include<bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
int pos[N];
int l, r;
int main()
{
int q;
scanf("%d", &q);
memset(pos, 0, sizeof(pos));
l = 0, r = 0;
while (q--)
{
char s[5];
scanf("%s", s);
int id;
scanf("%d", &id);
if (s[0] == 'L')
{
pos[id] = --l;
}
if (s[0] == 'R')
{
pos[id] = ++r;
}
if (s[0] == '?')
{
int ans;
if (pos[id] < 0)
{
ans = min(pos[id] - l, r - pos[id] - 1);
}
else
{
ans = min(pos[id] - l - 1, r - pos[id]);
}
printf("%d\n", ans);
}
}
return 0;
}
本文解析了一个关于书架操作的算法题目,通过记录书本放置位置,实现对书本左右侧书籍清空数量的快速查询。使用数组和指针跟踪最左、最右位置,以O(1)的时间复杂度完成查询。
1189

被折叠的 条评论
为什么被折叠?



