Codeforces 1070J Streets and Avenues in Berhattan dp

Streets and Avenues in Berhattan

我们首先能发现在最优情况下最多只有一种颜色会分别在行和列, 因为你把式子写出来是个二次函数, 在两端取极值。

然后我们就枚举哪个颜色会分别在行和列。 然后枚举这种颜色在行的个数, 再求出需要在列放的最少的这种颜色的个数。

这个我们可以用dp来check, dp[ i ] 表示 完整地加入若干种颜色能否恰好为 i , 然后再把dp[ i ]转成, 能组成大于等于 i 的最小值。

#include<bits/stdc++.h>
#define LL long long
#define LD long double
#define ull unsigned long long
#define fi first
#define se second
#define mk make_pair
#define PLL pair<LL, LL>
#define PLI pair<LL, int>
#define PII pair<int, int>
#define SZ(x) ((int)x.size())
#define ALL(x) (x).begin(), (x).end()
#define fio ios::sync_with_stdio(false); cin.tie(0);

using namespace std;

const int N = 2e5 + 7;
const int inf = 0x3f3f3f3f;
const LL INF = 0x3f3f3f3f3f3f3f3f;
const int mod = 1e9 + 7;
const double eps = 1e-8;
const double PI = acos(-1);

template<class T, class S> inline void add(T& a, S b) {a += b; if(a >= mod) a -= mod;}
template<class T, class S> inline void sub(T& a, S b) {a -= b; if(a < 0) a += mod;}
template<class T, class S> inline bool chkmax(T& a, S b) {return a < b ? a = b, true : false;}
template<class T, class S> inline bool chkmin(T& a, S b) {return a > b ? a = b, true : false;}

int n, m, k, dp[N];
int c[26];
char s[N];

void getDp(int ban) {
    for(int i = 0; i <= k; i++) dp[i] = 0;
    dp[0] = 1;
    for(int i = 0; i < 26; i++) {
        if(i == ban) continue;
        for(int j = k; j >= 0; j--) {
            if(dp[j]) dp[j + c[i]] |= dp[j];
        }
    }
    for(int i = k; i >= 0; i--) {
        if(dp[i]) dp[i] = i;
        else dp[i] = dp[i + 1];
    }
}

int main() {
    int T; scanf("%d", &T);
    while(T--) {
        memset(c, 0, sizeof(c));
        scanf("%d%d%d", &n, &m, &k);
        scanf("%s", s);
        for(int i = 0; s[i]; i++) c[s[i] - 'A']++;
        getDp(-1);
        if(k - dp[n] >= m) {
            puts("0");
        } else {
            LL ans = INF;
            for(int i = 0; i < 26; i++) {
                getDp(i);
                for(int j = 0; j <= c[i] && j <= n; j++) {
                    if(n - j > k - c[i]) continue;
                    int res = (k - c[i]) - dp[n - j];
                    if(m - res + j <= c[i])
                        chkmin(ans, 1LL * (m - res) * j);
                }
            }
            printf("%lld
", ans);
        }
    }
    return 0;
}

/*
*/
原文地址:https://www.cnblogs.com/CJLHY/p/10790947.html