题目大意
有一个滑道,由 个横向格子组成 ( 编号 到 ) 。开头的格子 和末尾的格子 固定为 x ,中间的格子由一个字符串给出,且仅包括 . 和 # 。我们有一个棋子,初始在编号为 的格子上,每秒会向右走一个格子。如果棋子走到了 x 上,会掉头;如果棋子走到了 . 上,会无事发生;如果棋子走到了 # 上,掉头的同时还会把 # 变成 . 。现在我们要计算:所有 # 变为 . 需要的时间。
思路分析
这题范围较大,考虑二分优化。
我们可以定义一个 set 来储存当前未处理的 # 的位置,因为 set 内部有序,可以直接二分查找最近的 # 的位置。再定义一个 来表示移动方向。
当 时,向右移动:我们二分查找棋子右侧距离最近的 # ,若存在就优先移动到该格并进行对应操作,若不存在就移动到右侧边界并掉头。当 时,向左移动,同理即可。
AC Code
十年OI一场空,不开【】一场空
#include<bits/stdc++.h>
using namespace std;
int N,A;
string S;
long long t;//不开【】只能得40pts
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> N >> A;
cin >> S;
set<int> st;
for(int i=1;i<=N;i++)
if(S[i-1] == '#')
st.insert(i);
int k=st.size();//'#'个数
int flag=1;
int pos=A;//表示当前棋子位置
while(k > 0)
{
if(flag == 1)//向右
{
auto it=st.upper_bound(pos);
int end_pos=N+1;
if(it != st.end() && *it < end_pos)
{
int x=*it;
t+=x-pos;
pos=x;
st.erase(it);
k--;
flag=-1;
}
else
{
t+=end_pos-pos;
pos=end_pos;
flag=-1;
}
}
else//向左
{
auto it=st.lower_bound(pos);
int end_pos=0;
int x=-1;
if(it != st.begin())
{
it--;
x=*it;
}
if(x != -1 && x > end_pos)
{
t+=pos-x;
pos=x;
st.erase(it);
k--;
flag=1;
}
else
{
t+=pos-end_pos;
pos=end_pos;
flag=1;
}
}
}
cout << t;
return 0;
}