URAL - 1745 Yet Another Answer 题解

· · 题解

题目大意

给定 n 个由括号组成的字符串 S_i,求:从中选出一些,连接成的合法括号串的最长长度。输出方案。

n\le1000, Σ{|S_i|}\le10000

分析

括号串的常用套路

记 sum_i(S) 为 吧 S 中 ( 当作 +1, ) 当作 -1,到第 i 位的前缀和。

一个合法的括号串 T,必须满足 sum_i(T)\ge0,且 sum_{|T|}(T) = 0。

显然对于一个不一定合法的括号串 S,我们只需要关注它的 min(-sum_i(S)),记为 b_i,和 sum_{|S|}(S),记作 d_i。例如,())(((中,d 值为 2,b 值为 1.

粗暴做法

由于要选出最长合法括号串,我们考虑 dp。最粗暴地,可以使用状压 dp,令 dp_{mask,i}表示目前选择了 mask 所表示的括号串,且 d 值为 j,的最大长度。复杂度 \mathcal{O}(n2^n)。

Exchange Argument

考虑使用 exchange argument。假设已经选择了一些括号串,已经保证连成的字符串 T 的 d 值为 0。我们要让 T 的 b 值尽可能小,从而尽量使其合法。很直观的策略是从左到右依次是 d_i>0, d_i=0, d_i<0,让 sum_i(T),尽量把中间抬高。

接下来是重点,d_i>0 的括号串之间如何决出前后。假如按照 ..., S_i, S_j, ... 的顺序排列。记 S_i 左边的串连起来的 d 值为 d_L。则 S_i 和 S_j 的总 b 值是 -min(d_L - b_i, d_L + d_i - b_j)。

假设我们交换 S_i 和 S_j,答案会变得更劣。显然邻项交换并不会使其他字符串影响合法性。唯一变化的是S_j 的总 b 值变成了 -min(d_L - b_j, d_L + d_j - b_i)。

连起来说,只要 -min(d_L - b_i, d_L + d_i - b_j) \le-min(d_L - b_j, d_L + d_j - b_i),S_i 放在 S_j 前面就是更优的。因此化简这个式子,问题就几乎解决了。

-min(d_L - b_i, d_L + d_i - b_j) \le-min(d_L - b_j, d_L + d_j - b_i) max(b_i, -d_i + b_j) \le max(b_j, -d_j + b_i) (b_i\le b_j\land-d_i + b_j \le b_j)\vee (b_i\le-d_j + b_i\land -d_i + b_j \le-d_j + b_i)

由于保证了 d_i > 0,式子后一半的 -d_i + b_j \le-d_j + b_i 恒不成立,式子前一半的 -d_i + b_j \le b_j 恒成立,故化简为 b_i\le b_j。因此 d_i\ge0 的括号串,按 b_i 递增排序。同理,d_i\le0 的括号串,按从右边意义上的 b 值排序,实际上是按 -d_i + b_i 递减排序。

至此,我们可以写出漂亮的 cmp 函数。

struct Word{
    int d, b, id, l; // 表示字符串的 d 值、b 值、输入时的编号、长度
    int sgn() const {
        if (d == 0) return 0;
        return (d > 0? 1: -1);
    }
    bool operator < (const Word &o){
        if (sgn() != o.sgn()) return sgn() > o.sgn();
        if (sgn() > 0) return b > o.b; // 我的 b 与上文的 b 是相反数
        if (sgn() < 0) return (b - d) < (o.b - o.d);
        return 0;
    }
};

背包 dp

接下来就是标准的背包 dp。令 dp_{i, j} 表示考虑到第 i 个括号串,且组成的括号串 d 值为 j,的最大长度。每次可以选或不选,因此有 dp_{i, j} \rightarrow dp_{i + 1, j} 和 dp_{i, j} + |S_i| \rightarrow dp_{i + 1, j + d_i} (j - b_i \ge 0)。过程中维护前继,用于回溯。最终输出 dp_{n, 0},并从这里回溯输出方案。时间复杂度 \mathcal{O}(n Σ|S_i|),可以通过。

我的代码

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef __int128 lll;
typedef pair <int, int> pii;
typedef pair <ll, ll> pll;
const int MOD = 998244353;

int n;
struct Word{
    int d, b, id, l;
    int sgn() const {
        if (d == 0) return 0;
        return (d > 0? 1: -1);
    }
    bool operator < (const Word &o){
        if (sgn() != o.sgn()) return sgn() > o.sgn();
        if (sgn() > 0) return b > o.b;
        if (sgn() < 0) return (b - d) < (o.b - o.d);
        return 0;
    }
} a[1005];
int dp[1005][5005], lst[1005][5005];

int main(){
    cin >> n;
    for (int i = 0; i < n; i++){
        string s; cin >> s;
        for (int j = 0; j < s.size(); j++){
            if (s[j] == '(') a[i].d++;
            else a[i].d--;
            a[i].b = min(a[i].b, a[i].d);
        }
        a[i].id = i;
        a[i].l = s.size();
    }
    sort(a, a + n);

    for (int i = 0; i <= n; i++) for (int j = 0; j <= 10000; j++) dp[i][j] = -1e9, lst[i][j] = -1;
    dp[0][0] = 0;

    for (int i = 0; i < n; i++){
        for (int j = 0; j <= 5000; j++){
            if (dp[i][j] == -1e9) continue;
            if (dp[i][j] > dp[i + 1][j]){
                dp[i + 1][j] = dp[i][j];
                lst[i + 1][j] = lst[i][j];
            }
            if (j + a[i].b >= 0 and j + a[i].d <= 5000 and dp[i][j] + a[i].l > dp[i + 1][j + a[i].d]){
                dp[i + 1][j + a[i].d] = dp[i][j] + a[i].l;
                lst[i + 1][j + a[i].d] = i;
            }
        }
    }

    cout << dp[n][0] << ' ';
    vector <int> ans;
    int x = n, y = 0;
    while (lst[x][y] != -1){
        int tmp = lst[x][y];
        ans.push_back(tmp);
        x = tmp;
        y -= a[tmp].d;
    }
    cout << ans.size() << "\n";
    for (int i = (int)ans.size() - 1; i >= 0; i--) cout << a[ans[i]].id + 1 << ' ';
    cout << "\n";

    return 0;
}

一些实现细节

这道题卡空间,如果 dp 开到 1000 \times 10000 会 MLE。考虑到如果把 d 值升到 5000 以上就无法再救回来,因此只需要开到 1000 \times 5000。

Deepseek 的修改

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

const int MAX_N = 1005;
const int MAX_BALANCE = 5000;
const int INF = -1e9;

struct Word {
    int balance;  // 总平衡度(左括号数 - 右括号数)
    int min_prefix; // 最小前缀和
    int id;       // 单词原始编号
    int length;   // 单词长度

    // 获取单词类型:正平衡返回1,负平衡返回-1,平衡返回0
    int getType() const {
        if (balance > 0) return 1;
        if (balance < 0) return -1;
        return 0;
    }

    // 排序比较函数
    bool operator < (const Word &other) {
        int type1 = getType();
        int type2 = other.getType();

        // 不同类型按正>零>负排序
        if (type1 != type2) return type1 > type2;

        // 正平衡单词:按最小前缀和降序
        if (type1 > 0) return min_prefix > other.min_prefix;

        // 负平衡单词:按 (min_prefix - balance) 升序
        if (type1 < 0) return (min_prefix - balance) < (other.min_prefix - other.balance);

        return false; // 平衡单词顺序任意
    }
};

int main() {
    int word_count;
    cin >> word_count;

    vector<Word> words(word_count);

    // 读取并处理每个单词
    for (int i = 0; i < word_count; i++) {
        string word_str;
        cin >> word_str;

        int current_balance = 0;
        int current_min_prefix = 0;

        // 计算单词的平衡度和最小前缀
        for (char c : word_str) {
            if (c == '(') current_balance++;
            else current_balance--;
            current_min_prefix = min(current_min_prefix, current_balance);
        }

        words[i] = {current_balance, current_min_prefix, i, (int)word_str.length()};
    }

    // 按特定规则排序单词
    sort(words.begin(), words.end());

    // 动态规划数组:dp[i][j] = 处理前i个单词,当前平衡度为j时的最大长度
    vector<vector<int>> dp(word_count + 1, vector<int>(MAX_BALANCE + 1, INF));
    vector<vector<int>> prev_index(word_count + 1, vector<int>(MAX_BALANCE + 1, -1));

    // 初始状态:0个单词,平衡度为0,长度为0
    dp[0][0] = 0;

    // 动态规划处理每个单词
    for (int i = 0; i < word_count; i++) {
        const Word &current_word = words[i];

        for (int balance = 0; balance <= MAX_BALANCE; balance++) {
            if (dp[i][balance] == INF) continue;

            // 选项1:不选当前单词
            if (dp[i][balance] > dp[i + 1][balance]) {
                dp[i + 1][balance] = dp[i][balance];
                prev_index[i + 1][balance] = prev_index[i][balance];
            }

            // 选项2:选当前单词(需要满足条件)
            int new_balance = balance + current_word.balance;
            if (balance + current_word.min_prefix >= 0 && 
                new_balance >= 0 && new_balance <= MAX_BALANCE && 
                dp[i][balance] + current_word.length > dp[i + 1][new_balance]) {

                dp[i + 1][new_balance] = dp[i][balance] + current_word.length;
                prev_index[i + 1][new_balance] = i;
            }
        }
    }

    // 输出结果
    int max_length = dp[word_count][0];
    cout << max_length << " ";

    // 回溯找到使用的单词
    vector<int> used_words;
    int current_index = word_count;
    int current_balance = 0;

    while (prev_index[current_index][current_balance] != -1) {
        int word_idx = prev_index[current_index][current_balance];
        used_words.push_back(word_idx);
        current_balance -= words[word_idx].balance;
        current_index = word_idx;
    }

    cout << used_words.size() << "\n";

    // 输出单词编号(注意反转顺序和+1处理)
    for (int i = (int)used_words.size() - 1; i >= 0; i--) {
        cout << words[used_words[i]].id + 1 << " ";
    }
    cout << "\n";

    return 0;
}

deepseek 把变量名改得更长了,但没有修改其他逻辑。实际写代码过程中,b,d 这两个变量名还是记得住的。如果问题更复杂,就需要学习 deepseek 的命名习惯,防止大脑混乱。

阶段视角

从状压 dp 到背包 dp,时空复杂度有巨大提升。本质上,这是使用 exchange argument,省去了不优的转移,使阶段划分更加清晰。