题解:AT_abc167_f [ABC167F] Bracket Sequencing

· · 题解

ABC167F Bracket Sequencing 的一种贪心策略

题目链接

算法思路

本题的目标是判断给定的括号序列能否通过重新拼接形成一个合法的括号序列。其他题解已详细介绍了序列的预处理方法,这里不再赘述。本文提出一种基于合并后序列长度的贪心策略,该策略通过比较不同排列方式下合并序列的长度,优先选择合并后长度较小的排列。

序列的表示

将每个括号序列预处理为一个有序对 (a, b)。其中:

合并规则

对于两个序列:

若将序列 1 放在序列 2 前面,合并后的新序列如下:

(a, b + d - c), & \text{if } b \geq c, \\ (a + c - b, d), & \text{if } b < c. \end{cases}

综合上述两种情况,合并后序列的长度可统一表示为:

L = a + |b - c| + d

贪心比较函数

在排序时,对于两个序列,选择合并后长度更小的排列方式就好了。

代码实现如下:

struct node{
    int a,b;

    node(int _a,int _b):a(_a),b(_b){}

    bool operator<(const node& other) const {
        int len1 = a + other.b + abs(b - other.a);  // 当前序列在前
        int len2 = other.a + b + abs(other.b - a);  // 其他序列在前
        return len1 < len2;
    }
};

算法步骤

  1. 预处理:遍历每个括号序列,统计其 (a, b) 值。
  2. 排序:使用上述比较函数对所有序列排序。
  3. 模拟合并:按排序顺序依次合并序列,检查最终结果是否为 (0, 0)(即合法括号序列)。

代码实现

#include<bits/stdc++.h>
using namespace std;
const int N=1e6+5;

struct node{
    int a,b;

    node(int _a,int _b):a(_a),b(_b){}

    bool operator<(const node& other) const {
        int len1 = a + other.b + abs(b - other.a);  // 当前序列在前
        int len2 = other.a + b + abs(other.b - a);  // 其他序列在前
        return len1 < len2;
    }
};

int n;
vector<node> l;
bool vis[N];

bool solve(){
    int a=l[0].a,b=l[0].b;
    for(auto it=l.begin()+1;it!=l.end();it++)//模拟合并一遍
    {
        if(b>=it->a)
            b+=it->b-it->a;
        else a+=it->a-b ,b=it->b;
    }
    if(!(a==0&&b==0))//判断
        return false;
    return true;
}

int main(){
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        string s;cin>>s;

        int sz=s.size(),a=0,b=0;
        for(int i=0;i<sz;i++)
            if(s[i]=='(')
                b++;
            else if(b) 
                b--;
            else a++;

        l.push_back({a,b});
    }

    sort(l.begin(),l.end());

    if(solve())
        cout<<"Yes\n";
    else cout<<"No\n";

    return 0;       
}

tips 这不是ai写的

  1. 本文使用了Gen AI优化了语言逻辑已经数学公式以及比较函数,已保证作者在文章中的贡献大于Gen AI 。

  2. 贪心策略是我意识流想出来的,没有证明,希望有大佬能够给出证明 或者证伪 。

  3. 作为第一篇题解,感谢管理大大通过 。