CF566A-贪心+字典树

题目大意:

给你两堆字符串,让你给他们两两匹配使得 L C P LCP LCP和最大。

题目思路:

首先的第一个想法:先将一堆字符串插到字典树里,之后将另一堆字符串,一个一个贪心查询尽量长的LCP,然后删除。

这样不正确,因为一旦你无法全部匹配,选择删哪一个就会有后效性.

第二个想法:在上面的基础上,先将第二堆LCP排序后再删。

这样显然又不对,删完以后其他字符串的LCP是动态变化的。也无法动态维护字符串的LCP。

考虑在字典树中的每个节点都保存含有该前缀的字符串们。这样就可以枚举LCP

如果我们从叶子节点一层一层往上处理,是不是就保证了处理的有顺序,从长到短处理。

换句话说:处理该节点之前,先让其子树节点先匹配完。剩下来无法匹配的字符串就只能在本LCP匹配了。

#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pii pair<int,int>
#define pb push_back
#define mp make_pair
#define vi vector<int>
#define vll vector<ll>
#define fi first
#define se second
const int maxn = 1e5 + 5;
const int mod = 1e9 + 7;
struct Node{
    int nxt[26];
    vector<int> q[2];
}tr[maxn * 8];
int cnt;
void add (string a , int t , int id){
    int n = a.size();
    int u = 0;
    tr[u].q[t].push_back(id);
    for (int i = 0 ; i < n ; i++){
        int v = a[i] - 'a';
        if (!tr[u].nxt[v]) tr[u].nxt[v] = ++cnt;
        u = tr[u].nxt[v];
        tr[u].q[t].push_back(id);
    }
}
int match[2][maxn] , ans;
void dfs (int u , int step){
    for (int i = 0 ; i < 26 ; i++)
        if (tr[u].nxt[i])
            dfs(tr[u].nxt[i] , step + 1);
    vector<int> t[2];
    for (int i = 0 ; i <= 1 ; i++)
        for (auto & g : tr[u].q[i])
            if (!match[i][g]) t[i].push_back(g);
    int n = min(t[0].size() , t[1].size());
    for (int i = 0 ; i < n ; i++) {
        match[0][t[0][i]] = t[1][i];
        match[1][t[1][i]] = t[0][i];
        ans += step;
    }
    return ;
}
int main()
{
    ios::sync_with_stdio(false);
    int n; cin >> n;
    for (int i = 1 ; i <= n ; i++){
        string a; cin >> a;
        add(a , 0 , i);
    }
    for (int i = 1 ; i <= n ; i++){
        string a; cin >> a;
        add(a , 1 , i);
    }
    dfs(0 , 0);
    cout << ans << endl;
    for (int i = 1 ; i <= n ; i++){
        cout << i << " " << match[0][i] << endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值