跳到正文

题解

题解:P18114 [入门赛 #54] 找搭档

Sunland_OIer约 5 分钟
原文
文章信息与版本

文章信息

发布
2026年11月27日
收录
2026年11月28日
更新
2026年11月28日
篇幅
约 5 分钟
题目
P18114

版本

  1. v1当前

思路

由于有在数列中删除的操作,不难想到链表。

可是每轮都要遍历一次,时间复杂度是 O(n2)O(n^2) 的,怎么办办呢?

我们发现,如果两个数原先相邻,且删除的块不与它们相邻,那么它们仍然会选择对方,不必重复计算。只需将每轮删除后左右又发生改变的数进行计算就可以。时间复杂度由 O(n2)O(n^2) 优化到了 O(n)O(n),可以通过此题。

AC Code
C++
#include <bits/stdc++.h>
using namespace std;
constexpr int N = 200005;
vector<pair<int,int>> check[N]; // 在第n轮需要检查是否会被删去的数的序列
int n,h[N],l[N],r[N],ans[N],times = 1;
bool ban[N]; // 是否是本轮需要考虑删除的数
bool choose(int u,int v) { // 判断是否选择对方
    int left = l[u],right = r[u];
    if(left == 0 && r == 0) return false;
    if(left == 0) return v == right;
    if(right == 0) return v == left;
    if(abs(h[u] - h[left]) <= abs(h[u] - h[right])) return v == left;
    return v == right;
}
int main(void) {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cin >> n;
    for(int i = 1;i <= n;i++)
        cin >> h[i];
    for(int i = 1;i <= n;i++)
        l[i] = i - 1,r[i] = i + 1;
    l[1] = 0,r[n] = 0;
    for(int i = 1;i < n;i++)
        check[1].push_back({i,i+1}); // 将第一轮每个数都加入检查数组
    while(times <= n) {
        vector<int> del; // 本轮确认被删除的数
        for(auto [u,v] : check[times]) { // 判断检查数组中的数是否会被删去
            if(ans[u] || ans[v]) continue;
            if(r[u] != v && r[v] != u) continue;
            if(ban[u] || ban[v]) continue;
            if(choose(u,v) && choose(v,u)) {
                ban[u] = ban[v] = true;
                del.push_back(u);
                del.push_back(v);
            }
        }
        if(del.empty()) break; // 若没有,说明结束
        for(int x : del) ans[x] = times;
        times++;
        for(int x : del) { // 将可能影响到的数加入下一轮的检查数组
            if(l[x] != 0 && ban[l[x]]) continue;
            int y = x;
            while(r[y] != 0 && ban[r[y]]) y = r[y];
            int left = l[x],right = r[y];
            if(left != 0) r[left] = right;
            if(right != 0) l[right] = left;
            if(left != 0 && right != 0) check[times].push_back({left,right});
            if(left != 0 && l[left] != 0) check[times].push_back({l[left],left});
            if(right != 0 && r[right] != 0) check[times].push_back({right,r[right]});
        }
        for(int x : del) ban[x] = false; // 本轮需要检查的数都检查完毕,不再是下回合需要考虑的数
    }
    for(int i = 1;i <= n;i++)
        cout << ans[i] << ' ';
    return 0;
}

AC记录

原文