[AtCoder Beginner Contest 175]-F - Making Palindrome(回文串+dijkstra)

[AtCoder Beginner Contest 175]-F - Making Palindrome(回文串+dijkstra)

题面:

题意:

给定\(\mathit n\) 个字符串,每一个字符串使用一次的成本是\(C_i\),每一个字符串可以使用多次,现在问你去选择一些字符串将其按照一定的顺序排列后拼接起来是一个回文串的最小成本是多少?

思路:

我们考虑从字符串的最左边或最右边构建字符串,首先,左侧和右侧均为空。

考虑对于每一个中间状态字符串\(now\),将给定字符串之一\(str\)附加到左侧或右侧。

如果\(str\)\(now\)应该回文匹配的部分不一致,则不能过渡到其他状态的。

通过此方法进行扩展虽然仅需要保留不是回文的字符串,但是仍然存在无限状态。

我们来考虑如果仅保留将字符串拼接时回文匹配后剩余的字符串,接下来的拼接只需要考虑这些字符串。

这样即可以保证正确性,又因为在最有的选择中,剩余的字符串应为给定字符串的前缀或后缀(数量为\(2\times \sum_{i=1}^{n}|s_i|\))。

我们可以把剩下的字符串视为顶点,顶点之间模拟回文匹配的方式建边,并使用Dijkstra方法顶点找到空字符串/回文距的距离,取最小者就是答案。

正确性的保证:

我们在转移过程中,额外维护一个回文匹配后剩余的字符串所需要在的位置,即字符串拼接过程中,可以将其放在左边或者右边,在一些匹配过程中可能剩余字符串就必须在接下来的拼接中在固定的位置才能保证答案的正确。

时间复杂度分析:

保留的字符串数量有\(O(n*L),L := \max |S|.\)

每次对于每一个回文匹配后剩余的字符串,我们枚举给定的字符串与其匹配\(O(n)\)

暴力模拟匹配\(O(L)\)

再考虑到dijkstra的时间复杂度,所以总体的时间复杂度为:\(O(\mathrm{O}(N^2 L (L + \log NL)))\)

代码:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <bits/stdc++.h>
#define ALL(x) (x).begin(), (x).end()
#define sz(a) int(a.size())
#define rep(i,x,n) for(int i=x;i<n;i++)
#define repd(i,x,n) for(int i=x;i<=n;i++)
#define pii pair<int,int>
#define pll pair<long long ,long long>
#define gbtb ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define MS0(X) memset((X), 0, sizeof((X)))
#define MSC0(X) memset((X), '\0', sizeof((X)))
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define eps 1e-6
#define chu(x)  if(DEBUG_Switch) cout<<"["<<#x<<" "<<(x)<<"]"<<endl
#define du3(a,b,c) scanf("%d %d %d",&(a),&(b),&(c))
#define du2(a,b) scanf("%d %d",&(a),&(b))
#define du1(a) scanf("%d",&(a));
using namespace std;
typedef long long ll;
ll gcd(ll a, ll b) {return b ? gcd(b, a % b) : a;}
ll lcm(ll a, ll b) {return a / gcd(a, b) * b;}
ll powmod(ll a, ll b, ll MOD) { if (a == 0ll) {return 0ll;} a %= MOD; ll ans = 1; while (b) {if (b & 1) {ans = ans * a % MOD;} a = a * a % MOD; b >>= 1;} return ans;}
ll poww(ll a, ll b) { if (a == 0ll) {return 0ll;} ll ans = 1; while (b) {if (b & 1) {ans = ans * a ;} a = a * a ; b >>= 1;} return ans;}
void Pv(const vector<int> &V) {int Len = sz(V); for (int i = 0; i < Len; ++i) {printf("%d", V[i] ); if (i != Len - 1) {printf(" ");} else {printf("\n");}}}
void Pvl(const vector<ll> &V) {int Len = sz(V); for (int i = 0; i < Len; ++i) {printf("%lld", V[i] ); if (i != Len - 1) {printf(" ");} else {printf("\n");}}}
inline long long readll() {long long tmp = 0, fh = 1; char c = getchar(); while (c < '0' || c > '9') {if (c == '-') fh = -1; c = getchar();} while (c >= '0' && c <= '9') tmp = tmp * 10 + c - 48, c = getchar(); return tmp * fh;}
inline int readint() {int tmp = 0, fh = 1; char c = getchar(); while (c < '0' || c > '9') {if (c == '-') fh = -1; c = getchar();} while (c >= '0' && c <= '9') tmp = tmp * 10 + c - 48, c = getchar(); return tmp * fh;}
void pvarr_int(int *arr, int n, int strat = 1) {if (strat == 0) {n--;} repd(i, strat, n) {printf("%d%c", arr[i], i == n ? '\n' : ' ');}}
void pvarr_LL(ll *arr, int n, int strat = 1) {if (strat == 0) {n--;} repd(i, strat, n) {printf("%lld%c", arr[i], i == n ? '\n' : ' ');}}
const int maxn = 1000010;
const ll inf = 1e18;
/*** TEMPLATE CODE * * STARTS HERE ***/
#define DEBUG_Switch 0
int n;
string a[55];
ll c[55];
map<string, int> sid;
int ispal[maxn];
bool check(string str)
{
    string temp = str;
    reverse(ALL(temp));
    return temp == str;
}
ll dis[2][maxn];
struct Date
{
    ll cost;
    int dir;
    int id;
    Date() {}
    Date(ll cc, int dd, int ii)
    {
        cost = cc;
        dir = dd;
        id = ii;
    }
    bool operator < (const Date & b) const
    {
        return cost > b.cost;
    }
};
priority_queue<Date> q;
int main()
{
#if DEBUG_Switch
    freopen("C:\\code\\input.txt", "r", stdin);
#endif
    //freopen("C:\\code\\output.txt","w",stdout);
    cin >> n;
    repd(i, 1, n)
    {
        cin >> a[i] >> c[i];
    }
    ll ans = inf;
    repd(i, 1, n)
    {
        string temp = a[i];
        reverse(ALL(temp));
        if (temp == a[i])
        {
            ans = min(ans, c[i]);
        }
        temp = "";
        int m = sz(a[i]);
        repd(j, 0, m - 1)
        {
            temp.push_back(a[i][j]);
            if (sid.count(temp) == 0)
            {
                sid[temp] = sz(sid);
            }
        }
        temp = "";
        for (int j = m - 1; j >= 0; --j)
        {
            temp = a[i][j] + temp;
            if (sid.count(temp) == 0)
            {
                sid[temp] = sz(sid);
            }
        }
    }
    std::vector<string> v(sz(sid) + 10);
    for (auto s : sid)
    {
        ispal[s.se] = check(s.fi);
        dis[0][s.se] = dis[1][s.se] = inf;
        v[s.se] = s.fi;
    }
    repd(i, 1, n)
    {
        int id = sid[a[i]];
        dis[0][id] = dis[1][id] = c[i];
        q.push(Date(c[i], 0, id));
        q.push(Date(c[i], 1, id));
    }
    while (!q.empty())
    {
        Date temp = q.top();
        q.pop();
        if (dis[temp.dir][temp.id] < temp.cost)
            continue;
        repd(i, 1, n)
        {
            string left = v[temp.id];
            string right = a[i];
            if (temp.dir)
                swap(left, right);
            int pos = 0;
            while (pos < min(sz(left), sz(right)))
            {
                if (left[pos] == right[sz(right) - 1 - pos])
                {
                    pos++;
                } else
                {
                    break;
                }
            }
            if (pos < min(sz(left), sz(right)))
                continue;
            ll nd = temp.cost + c[i];
            if (pos == sz(left) && pos == sz(right))
            {
                ans = min(ans, nd );
            } else if (pos == sz(left))
            {
                string rm = right.substr(0, sz(right) - pos);
                if (ispal[sid[rm]])
                {
                    ans = min(ans, nd);
                } else
                {
                    int nowid = sid[rm];
                    if (dis[1][nowid] > nd)
                    {
                        dis[1][nowid] = nd;
                        q.push(Date(nd, 1, nowid));
                    }
                }
            } else
            {
                string rm = left.substr(pos);
                if (ispal[sid[rm]])
                {
                    ans = min(ans, nd);
                } else
                {
                    int nowid = sid[rm];
                    if (dis[0][nowid] > nd)
                    {
                        dis[0][nowid] = nd;
                        q.push(Date(nd, 0, nowid));
                    }
                }
            }
        }
    }
    if (ans == inf)
    {
        cout << -1 << endl;
    } else
    {
        cout << ans << endl;
    }
    return 0;

}



posted @ 2020-09-01 23:53  茄子Min  阅读(309)  评论(0编辑  收藏  举报