跳到正文

题解

题解:AT_abc395_d [ABC395D] Pigeon Swap

__youzimo2014__约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 2 分钟

版本

  1. v1当前

思路

首先这道题如果没有操作 22,那么只需要存储每一只鸽子所在的巢穴即可。

问题来了,怎么进行操作 22?

朴素算法:把每一只在 aa 巢穴的鸽子所在巢穴编号改为 bb,在 bb 巢穴的鸽子同理。

把每一只在 aa 巢穴的鸽子所在巢穴编号改为 bb,你会想到什么?

没错,指针。

我们只需要把每一个鸽子指向一个巢穴,在交换的时候将两个巢穴的编号交换即可。

我们还需要维护每一个编号所对应的巢穴指针。

Code

C++
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 5;
struct Nest {
    int id;
    Nest(int id_) {
        id = id_;
    }
};
Nest *nests[N]; // nests[i] 表示第 i 个巢穴。
Nest *where[N]; // where[i] 表示第 i 只鸽子所在的巢穴。
int main() {
    int n, q;
    cin >> n >> q;
    for (int i = 1; i <= n; i++) {
        nests[i] = where[i] = new Nest(i);
    }
    while (q--) {
        int op; cin >> op;
        if (op == 1) {
            int a, b; cin >> a >> b;
            where[a] = nests[b];
        } else if (op == 2) {
            int a, b; cin >> a >> b;
            nests[a] -> id = b;
            nests[b] -> id = a;
            swap(nests[a], nests[b]);
        } else {
            int a; cin >> a;
            cout << where[a] -> id << endl;
        }
    }
    return 0;
}
原文