跳到正文

题解

题解:P8108 [Cnoi2021] 绀珠传说

andrew_201约 3 分钟
原文
文章信息与版本

文章信息

发布
2026年4月22日
收录
2026年7月15日
更新
2026年11月14日
篇幅
约 3 分钟
获赞
1
题目
P8108

版本

  1. v1当前

前言

这并非最优解。

题目传送门

题目大意

有一个 n×nn×n 的网格,每个格子有一颗珠子,共有 nn 种颜色,每种颜色恰好出现 nn 次,随机分布。每次操作可以选择最底一行中若干个连续且颜色相同的珠子消除,消除后上方珠子下落。求消除所有珠子的最少操作次数。

解题思路

由于数据随机,可以采用贪心策略:每次扫描当前最底一行,将连续同色的段依次消除,统计步数。

虽然贪心不一定全局最优,但在随机数据下通常能得到正确答案,且实现简单。

若需严格最优解,则需区间 DP,状态为 dp[l][r][k] 表示清空第 ll 到 rr 列且当前底部在第 kk 行的最小步数,但 n≤1000n≤1000 时三维状态过大,实际比赛中常采用贪心通过随机数据。

code

C++
#include <bits/stdc++.h>
using namespace std;

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

    int n;
    cin >> n;
    vector<vector<int>> a(n, vector<int>(n));
    for (int i = 0; i < n; ++i)
        for (int j = 0; j < n; ++j)
            cin >> a[i][j];

    int ans = 0;
    vector<int> height(n, n); // 每列剩余珠子数

    while (true) {
        bool empty = true;
        for (int j = 0; j < n; ++j)
            if (height[j] > 0) {
                empty = false;
                break;
            }
        if (empty) break;

        int j = 0;
        while (j < n) {
            if (height[j] == 0) {
                ++j;
                continue;
            }
            int color = a[n - height[j]][j]; // 当前底部珠子颜色
            int k = j;
            while (k < n && height[k] > 0 && a[n - height[k]][k] == color)
                ++k;
            // 消除 [j, k-1]
            ++ans;
            for (int col = j; col < k; --height[col], ++col);
            j = k;
        }
    }

    cout << ans << "\n";
    return 0;
}

完结撒花*★,°:.☆( ̄▽ ̄)/$:.°★* 。

原文