前言
这并非最优解。
题目大意
有一个 的网格,每个格子有一颗珠子,共有 种颜色,每种颜色恰好出现 次,随机分布。每次操作可以选择最底一行中若干个连续且颜色相同的珠子消除,消除后上方珠子下落。求消除所有珠子的最少操作次数。
解题思路
由于数据随机,可以采用贪心策略:每次扫描当前最底一行,将连续同色的段依次消除,统计步数。
虽然贪心不一定全局最优,但在随机数据下通常能得到正确答案,且实现简单。
若需严格最优解,则需区间 DP,状态为 dp[l][r][k] 表示清空第 到 列且当前底部在第 行的最小步数,但 时三维状态过大,实际比赛中常采用贪心通过随机数据。
code
#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;
}完结撒花*★,°:.☆( ̄▽ ̄)/$:.°★* 。