当前位置:实例文章 » 其他实例» [文章]P2926 [USACO08DEC] Patting Heads S

P2926 [USACO08DEC] Patting Heads S

发布人:shili8 发布时间:2025-02-14 04:47 阅读次数:0

**Patting Heads**

**Problem Description**

在一个有 $n$ 个人的场景中,每个人都有一颗头。每个人都可以向左或右移动一步,或者不动。现在,我们需要找到从第一个人开始,按照某种顺序让所有人都摸到自己的头的最短时间。

**Problem Constraints**

* $1 leq n leq100$
* 每个人只能向左或右移动一步**Solution**

我们可以使用一个队列来模拟这个过程。每次从队列中取出一个人,然后将他放回队列的末尾(表示他摸到了自己的头)。如果队列为空,则说明所有人都摸到了自己的头。

cpp#include <iostream>
#include <queue>

using namespace std;

const int N =105;
int n, ans;

struct Node {
 int x, y; // x: id, y: time};

bool cmp(const Node &a, const Node &b) { return a.y < b.y; }

void solve() {
 cin >> n;
 priority_queue<Node> q;
 for (int i =1; i <= n; ++i) {
 q.push({i,0});
 }
 int t =0;
 while (!q.empty()) {
 Node u = q.top();
 q.pop();
 if (u.y == t) {
 ans++;
 t +=2;
 } else {
 q.push(u);
 }
 }
}

int main() {
 ios::sync_with_stdio(false);
 cin.tie(nullptr);

 int T =1; // cin >> T;
 while (T--) {
 solve();
 cout << ans << '
';
 ans =0;
 }

 return0;
}


**Explanation**

* 我们使用一个优先队列来模拟这个过程,每次从队列中取出一个人,然后将他放回队列的末尾(表示他摸到了自己的头)。
* 如果队列为空,则说明所有人都摸到了自己的头。
* 每次从队列中取出一个人时,我们检查他的时间是否等于当前时间。如果是,则我们增加答案并更新当前时间。否则,我们将其放回队列的末尾。

**Time Complexity**

* 每次从队列中取出一个人的时间复杂度为 O(log n)。
* 我们重复这个过程 n 次,因此总时间复杂度为 O(n log n)。

**Space Complexity**

* 我们使用一个优先队列来存储所有人,空间复杂度为 O(n)。

相关标签:
其他信息

其他资源

Top