CF 601D(Acyclic Organic Compounds-字典树)

给一颗n(1 ≤ n ≤ 300 000)个节点的树,root=1,每个节点上有一个字母,每个子树从根开始向下遍历到任意节点停下,经过的不同字符串个数为diff[i],
已知 ci ,求 max(diffi+ci)i

求出 diffi 就行
考虑给每个子树建一颗字典树,然后不断合并字典树
然后优先让节点数大的向小的合并

#include<bits/stdc++.h>
using namespace std;
#define For(i,n) for(int i=1;i<=n;i++)
#define Fork(i,k,n) for(int i=k;i<=n;i++)
#define Rep(i,n) for(int i=0;i<n;i++)
#define ForD(i,n) for(int i=n;i;i--)
#define ForkD(i,k,n) for(int i=n;i>=k;i--)
#define RepD(i,n) for(int i=n;i>=0;i--)
#define Forp(x) for(int p=Pre[x];p;p=Next[p])
#define Forpiter(x) for(int &p=iter[x];p;p=Next[p]) 
#define Lson (o<<1)
#define Rson ((o<<1)+1)
#define MEM(a) memset(a,0,sizeof(a));
#define MEMI(a) memset(a,127,sizeof(a));
#define MEMi(a) memset(a,128,sizeof(a));
#define INF (2139062143)
#define F (100000007)
#define pb push_back
#define mp make_pair 
#define fi first
#define se second 
typedef long long ll;
typedef vector<int> vi;
typedef unsigned long long ull;
ll mul(ll a,ll b){return (a*b)%F;}
ll add(ll a,ll b){return (a+b)%F;}
ll sub(ll a,ll b){return (a-b+llabs(a-b)/F*F+F)%F;}
void upd(ll &a,ll b){a=(a%F+b%F)%F;}
int read()
{
    int x=0,f=1; char ch=getchar();
    while(!isdigit(ch)) {if (ch=='-') f=-1; ch=getchar();}
    while(isdigit(ch)) { x=x*10+ch-'0'; ch=getchar();}
    return x*f;
} 
#define MAXN (300000+10)
int n;
ll c[MAXN];
char s[MAXN];
vi e[MAXN];
struct node{
    map<int, node* > g; 
}pool[1000000],*cur=pool,*rt[MAXN];
stack<node*> trans;
node* newnode() {
    if (!trans.empty()) {
        node *p=trans.top(); p->g.clear();
        trans.pop();
        return p;
    }
    return cur++;
}

int diff[MAXN]={0},sz[MAXN];
vi son[MAXN];
int cmp(int a,int b) {return sz[a]>sz[b];}

void Merge(node *a,node *b,int &ans)
{
    for (auto v:b->g) {
        if (a->g.find(v.fi)==a->g.end()) {
            ++ans; a->g[v.fi]=newnode(); 
        }
        Merge(a->g[v.fi],v.se,ans);
    }
    trans.push(b);
}

void dfs(int x,int f){
    for(auto v:e[x]) {
        if (v==f) continue;
        dfs(v,x);
        son[x].pb(v); sz[x]+=sz[v];
    }
    sz[x]++;
    if (sz[x]==1) {
        rt[x]=newnode(); 
        diff[x]=1;
        rt[x]->g[s[x]-'a']=newnode();
        return;     
    }
    sort(son[x].begin(),son[x].end(),cmp);
    int m=son[x].size();
    node *p=rt[son[x][0]];
    diff[x]=diff[son[x][0]]+1;
    for(int i=1;i<m;i++) {
        Merge(p,rt[son[x][i]],diff[x]);         
    }
    rt[x]=newnode(); 
    rt[x]->g[s[x]-'a']=p;
    return; 
}



int main()
{
// freopen("CF601D.in","r",stdin);
// freopen(".out","w",stdout);

    n=read();
    For(i,n) c[i]=read();
    scanf("%s",s+1);
    For(i,n-1) {
        int u=read(),v=read();
        e[u].pb(v);  
        e[v].pb(u);
    }
    dfs(1,0);
    ll ma=diff[1]+c[1];
    For(i,n) ma=max(ma,diff[i]+c[i]);
    int ans=0;
    For(i,n) if (diff[i]+c[i]==ma) ++ans;
    cout<<ma<<endl<<ans<<endl;

    return 0;
}

你可能感兴趣的:(字典树)