题解:CF237E Build String

· · 题解

前置芝士:费用流。

图论建模,考虑利用网络流中管道的限流特性来刻画本题中的若干限制条件。

建立虚拟源点 S,虚拟汇点 T。

跑最小费用最大流即可。

CODE

#include<bits/stdc++.h>
#define int long long
#define void inline void
using namespace std;
const int maxn = 6003, inf = 1e16;
string str;
int n, N, tot = 1, s, t;
int h[maxn], to[maxn], w[maxn], nxt[maxn], dis[maxn], flow[maxn], c[maxn], pre[maxn], cid[30], a[30], sid[maxn];
bool vis[maxn];
queue<int> q;
void add(int x, int y, int z, int Z)
{
    to[++tot] = y;
    w[tot] = z;
    c[tot] = Z;
    nxt[tot] = h[x];
    h[x] = tot;
}
bool spfa()
{
    for (int i = 1; i <= N; i++)
    {
        dis[i] = inf;
        vis[i] = 0;
    }
    dis[s] = 0;
    q.push(s);
    vis[s] = 1;
    flow[s] = inf;
    while (!q.empty())
    {
        int now = q.front();
        q.pop();
        vis[now] = 0;
        for (int i = h[now]; i; i = nxt[i])
        {
            int j = to[i];
            if (w[i] && dis[j] > dis[now] + c[i])
            {
                dis[j] = dis[now] + c[i];
                flow[j] = min(flow[now], w[i]);
                pre[j] = i;
                if (!vis[j])
                {
                    vis[j] = 1;
                    q.push(j);
                }
            }
        }
    }
    return dis[t] < inf;
}
signed main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin >> str;
    s = ++N, t = ++N;
    for (char i : str)
    {
        a[i - 'a']++;
    }
    for (int i = 0; i < 26; i++)
    {
        cid[i] = ++N;
        add(N, t, a[i], 0);
        add(t, N, 0, 0);
    }
    cin >> n;
    for (int i = 1; i <= n; i++)
    {
        string syh;
        cin >> syh;
        memset(a, 0, sizeof(a));
        for (char j : syh)
        {
            a[j - 'a']++;
        }
        int x;
        cin >> x;
        sid[i] = ++N;
        add(s, N, x, i);
        add(N, s, 0, -i);
        for (int j = 0; j < 26; j++)
        {
            if (a[j])
            {
                add(N, cid[j], a[j], 0);
                add(cid[j], N, 0, 0);
            }
        }
    }
    int ansa = 0, ansb = 0;
    while (spfa())
    {
        ansa += flow[t], ansb += flow[t] * dis[t];
        for (int i = t; i != s; i = to[pre[i] ^ 1])
        {
            w[pre[i]] -= flow[t];
            w[pre[i] ^ 1] += flow[t];
        }
    }
    if (ansa != str.size())
    {
        cout << -1;
    }
    else
    {
        cout << ansb;
    }
    return 0;
}