157 字
1 分钟
题解:AT_abc471_c [ABC471C] Cookies and Greedy Takahashi

思路#

考虑用一个 set 维护所有还没有被拾取的饼干坐标。

设当前位于 curcur,那么我们可以用 lower_bound 找到右侧最近的饼干,它的前一个位置就是左侧最近的饼干。根据题意,比较两者的距离,如果距离相同就取左侧饼干。然后把取的饼干删除并更新当前位置即可。

Code#

#include<bits/stdc++.h>
using namespace std;
#define int long long
int n,cur,ans;
set<int> a;
signed main() {
ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
cin>>n;
for (int i=1,x;i<=n;i++)
cin>>x,a.insert(x);
while (!a.empty()) {
auto r=a.lower_bound(cur);
int nxt;
if (r==a.begin()) nxt=*r;
else if (r==a.end()) r--,nxt=*r;
else {
auto l=r;
l--;
if (cur-*l<=*r-cur) nxt=*l;
else nxt=*r;
}
ans+=abs(nxt-cur);
cur=nxt;
a.erase(cur);
}
cout<<ans;
return 0;
}
题解:AT_abc471_c [ABC471C] Cookies and Greedy Takahashi
https://banglee13.github.io/posts/atabc471c/
作者
banglee
发布于
2026-08-16
许可协议
CC BY-NC-SA 4.0

分享文章

生成精美分享图或复制链接,与更多人分享本文。

继续阅读

沿着主题读

基于共同的标签与分类

换条路线

从其他文章中稳定抽取

最后更新于 ,距今已过 101 天

部分内容可能已过时