P7861 [COCI 2015/2016 #2] SAVEZ 详解

· · 题解

题意

一般来说我没有描述题意的习惯,但是我这回得描述一下,因为样例会误导人。

给你一些字符串,你需要构造一个序列 a,使得序列中的每一对 i < j,都有 a_i < a_j,且 x_{a_i} 一个字母不落地全部出现在 x_{a_j} 的开头和结尾,求这个序列的最长长度。

思路

很明显如果说 i < j < k,那么 x_{a_j} 包含在 x_{a_k} 中,因为 x_{a_i} 包含在 x_{a_j} 中,所以 x_{a_i} 必定包含在 x_{a_k} 中。

比较朴素的想法,考虑前面的每个字符串,然后看当前的字符串能不能拼在前面的字符串所在最长序列的后面。这里有个小贪心,为什么是最长的序列,因为既然都是包含关系,必然不会影响后面接上的字符串,所以选择最长的。

但是不对,因为时间复杂度是平方的。

我们继续观察,发现只有当前面一部分和后面一部分相同的时候才后可能匹配上字符串。到这个地方,当前字符串需要自我匹配,还需要匹配前面的字符串,很难不想到哈希。

开一个 map,将哈希值映射到对应字符串所在的最长序列的长度,用两个指针从前后开始扫,如果说这个点的哈希值相同,说明当前的字串可能对应一个字符串,然后用对应 map 值加一更新当前答案,最后把自己哈希值对应的答案改掉。

代码还是很简单的,时间复杂度 O(\sum |x_i| \log{n}),轻松跑到最优解。

Code

//# pragma GCC optimize("Ofast")
# include <bits/stdc++.h>
# define fr front
# define il inline
# define fir first
# define sec second
# define vec vector
# define it iterator
# define pb push_back
# define lb lower_bound
# define ub upper_bound
# define all(x) x.begin(), x.end()
# define mem(a, b) memset(a, b, sizeof(a))

# define lc (t[p].l)
# define rc (t[p].r)
# define ls(x) (x << 1)
# define rs(x) (x << 1 | 1)
# define lson ls(p), l, mid
# define rson rs(p), mid + 1, r

# define sqr(x) ((x) * (x))
# define bpc __builtin_popcount
# define lowbit(x) ((x) & (-(x)))
# define geti(x, i) (((x) >> (i)) & 1)
# define set1(x, i) ((x) | (1 << (i)))
# define set0(x, i) ((x) & (~(1 << (i))))

# define debug1(x) cerr << #x << " = " << x << " "
# define debug2(x) cerr << #x << " = " << x << "\n"
# define bug cerr << "--------------------------\n"

# define each1(i, x) for(auto (i) : (x))
# define each2(i, x) for(auto (&i) : (x))
# define rep(i, a, b) for(int i = (a); i <= (b); ++ i)
# define pre(i, a, b) for(int i = (a); i >= (b); -- i)
# define G(i, h, u, ne) for(int i = (h[(u)]); i; i = (ne[(i)]))
# define reps(i, a, b, c) for(int i = (a); i <= (b); i += (c))
# define pres(i, a, b, c) for(int i = (a); i >= (b); i -= (c))
using namespace std;

using DB = double;
using LL = long long;
using LDB = long double;
using PII = pair<int, int>;
using ULL = unsigned long long;

const int N = 2e6 + 10, P = 13331;
const int INF1 = 0x3f3f3f3f, INF2 = INT_MAX;
const LL INF3 = (LL)1e18, INF4 = 0x3f3f3f3f3f3f3f3f, INF5 = LLONG_MAX;

int n, m, mx, ans;
char s[N];

ULL h1, h2, mul[N];

map<ULL, int> mp;//hash值映射到序列长度 

signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);

    cin >> n;
    mul[0] = 1;
    rep(i, 1, N - 10) mul[i] = mul[i - 1] * P;

    while(n --){
        cin >> s + 1;
        m = strlen(s + 1);
        int i = 1, j = m;
        mx = 1;
        h1 = h2 = 0;
        while(i <= m){
            h1 = h1 * P + s[i];
            h2 = h2 + mul[m - j] * s[j];
            if(h1 == h2){
                mx = max(mx, mp[h1] + 1);
            }

            i ++, j --;
        }

//      rep(i, 1, m) cout << s[i];
//      cout << " " << h1 << " " << h2 << "\n";
        mp[h1] = mx;
        ans = max(ans, mx);
    }

    cout << ans;

    return 0;
}

心裡的眼淚模糊了視線,你已快看不見……