18063 圈中的游戏

### 思路

这个问题是经典的约瑟夫环问题。我们可以使用链表来模拟这个过程。具体步骤如下:
1. 创建一个循环链表,表示所有人。
2. 从第一个人开始,依次报数。
3. 每报到3的人退出圈子,直到只剩下一个人。

### 伪代码

```
function josephus(n):
    create a circular linked list with n nodes
    current = head of the list

    while more than one node in the list:
        move current to the next node twice (to skip two nodes)
        remove the node after current (the third node)

    return the value of the remaining node
```

### C++代码

#include <iostream>

struct Node {
    int data;
    Node* next;
    Node(int val) : data(val), next(nullptr) {}
};

int josephus(int n) {
    if (n == 1) return 1;

    // Create a circular linked list of size n
    Node* head = new Node(1);
    Node* prev = head;
    for (int i = 2; i <= n; ++i) {
        prev->next = new Node(i);
        prev = prev->next;
    }
    prev->next = head; // Make it circular

    // Start from the head
    Node* current = head;
    while (current->next != current) {
        // Move to the node before the one to be removed
        current = current->next->next;
        // Remove the node after current
        Node* temp = current->next;
        current->next = temp->next;
        delete temp;
    }

    int result = current->data;
    delete current;
    return result;
}

int main() {
    int n;
    std::cin >> n;
    std::cout << josephus(n) << std::endl;
    return 0;
}

### 总结

通过使用循环链表,我们可以有效地模拟报数和删除操作。每次报数到3时,删除相应的节点,直到只剩下一个节点。这个方法的时间复杂度是O(n),适合处理较大的输入规模。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值