[贪心+Trie] Codeforces #566A. Matching Names

首先考虑直觉的贪心,每次找 LCP 尽量长的配对。是否正确呢?
考虑 a b LCP 较长, c d 较短,如果我们互换组合,一定不会使答案增大,所以大概可以感受到贪心是对的。
接下来就是实现的问题了。容易想到 Trie 。我们可以从叶往根合并,中途进行匹配。

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<string>
#include<vector>
#include<cstring>
using namespace std;
const int maxn=100005;
int n,ans,tot;
string a[maxn],b[maxn];
pair<int,int> res[maxn];
struct node{
    node* ch[26];
    vector<int> V1,V2;
    node(){ memset(ch,0,sizeof(ch));V1.clear();V2.clear(); }
} base[500000], *p_top=base, *root;
typedef node* P_node;
P_node newnode(){ return p_top++; }
void Insert1(int id,string st){
    P_node now=root;
    for(int i=0;i<st.size();i++){
        if(!now->ch[st[i]-'a']) now->ch[st[i]-'a']=newnode();
        now=now->ch[st[i]-'a']; 
    }
    now->V1.push_back(id);
}
void Insert2(int id,string st){
    P_node now=root;
    for(int i=0;i<st.size();i++){
        if(!now->ch[st[i]-'a']) now->ch[st[i]-'a']=newnode();
        now=now->ch[st[i]-'a']; 
    }
    now->V2.push_back(id);
}
typedef node* P_node;
void dfs(P_node p,int dep){
    for(int i=0;i<=25;i++) if(p->ch[i]){
        dfs(p->ch[i],dep+1); 
        for(auto j : p->ch[i]->V1) p->V1.push_back(j);
        for(auto j : p->ch[i]->V2) p->V2.push_back(j);
    }
    while(p->V1.size()&&p->V2.size()){
        ans+=dep;
        res[++tot]=make_pair(p->V1[p->V1.size()-1],p->V2[p->V2.size()-1]);
        p->V1.pop_back(); p->V2.pop_back();
    }
}
int main(){
    freopen("51nod1526.in","r",stdin);
    freopen("51nod1526.out","w",stdout);
    scanf("%d",&n);
    root=newnode();
    for(int i=1;i<=n;i++) cin >> a[i], Insert1(i,a[i]);
    for(int i=1;i<=n;i++) cin >> b[i], Insert2(i,b[i]);
    dfs(root,0);
    printf("%d\n",ans);
    for(int i=1;i<=n;i++) printf("%d %d\n",res[i].first,res[i].second);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值