bzoj4922 [Lydsy1706月赛]Karp-de-Chant Number 贪心+背包

题目传送门

https://lydsy.com/JudgeOnline/problem.php?id=4922

题解

记录每一个串的没有匹配的右括号 \()\) 的数量为 \(a_i\),为匹配的左括号 \((\) 的数量为 \(b_i\)

\(h\) 表示前面的所有括号序列的剩下的未匹配的左括号 \((\)。可以发现,每一个串的作用就是先让 \(h\) 减少 \(a_i\),如果 \(h \geq 0\),那么再让 \(h\) 增加 \(b_i\)

这是一种很常见的贪心模型,类似于 https://lydsy.com/JudgeOnline/problem.php?id=4619 的贪心策略,对于 \(a_i \leq b_i\) 的,需要尽量让每一个都可以选上,因此要把 \(a_i\) 从小到大排序,以便最后获得尽量大的 \(\max h\)

对于 \(a_i > b_i\) 的,需要尽量让需要的前置 \(h\) 尽量小,因此把 \(b_i\) 从大到小排序。

最后总体上,\(a_i \leq b_i\) 的排在前面。

然后就是一个对于 \(h\) 的 01 背包了。


下面是代码,时间复杂度 \(O(n^3)\)

#include<bits/stdc++.h>

#define fec(i, x, y) (int i = head[x], y = g[i].to; i; i = g[i].ne, y = g[i].to)
#define dbg(...) fprintf(stderr, __VA_ARGS__)
#define File(x) freopen(#x".in", "r", stdin), freopen(#x".out", "w", stdout)
#define fi first
#define se second
#define pb push_back

template<typename A, typename B> inline char smax(A &a, const B &b) {return a < b ? a = b, 1 : 0;}
template<typename A, typename B> inline char smin(A &a, const B &b) {return b < a ? a = b, 1 : 0;}

typedef long long ll; typedef unsigned long long ull; typedef std::pair<int, int> pii;

template<typename I> inline void read(I &x) {
    int f = 0, c;
    while (!isdigit(c = getchar())) c == '-' ? f = 1 : 0;
    x = c & 15;
    while (isdigit(c = getchar())) x = (x << 1) + (x << 3) + (c & 15);
    f ? x = -x : 0;
}

const int N = 300 + 7;
const int M = 90000 + 7;
const int INF = 0x3f3f3f3f;

int n, m;
char s[N];
int dp[M];

struct Qthx {
    int a, b, len;
    inline bool operator < (const Qthx &c) const {
        if (a < b) {
            if (c.a < c.b) return a < c.a;
            else return 1;
        } else {
            if (c.a < c.b) return 0;
            else return b > c.b;
        }
    }
} c[N];

inline void work() {
    std::sort(c + 1, c + n + 1);
    for (int i = 1; i <= m; ++i) dp[i] = -INF;
    for (int i = 1; i <= n; ++i) {
        if (c[i].b > c[i].a) for (int j = m; j >= c[i].b; --j) smax(dp[j], dp[j + c[i].a - c[i].b] + c[i].len);
        else for (int j = c[i].b; j <= m; ++j) smax(dp[j], dp[j + c[i].a - c[i].b] + c[i].len);
    }
    printf("%d\n", dp[0]);
}

inline void init() {
    read(n);
    for (int i = 1; i <= n; ++i) {
        scanf("%s", s + 1);
        int a = 0, b = 0;
        for (int j = 1; s[j]; ++j) {
            if (s[j] == '(') ++b;
            else {
                if (b) --b;
                else ++a;
            }
            ++c[i].len;
        }
        c[i].a = a, c[i].b = b, m += std::max(0, b - a);
    }
}

int main() {
#ifdef hzhkk
    freopen("hkk.in", "r", stdin);
#endif
    init();
    work();
    fclose(stdin), fclose(stdout);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/hankeke/p/bzoj4922.html