45pts求助

P4683 [IOI2008] Type Printer

Star_V @ 2023-07-29 15:47:34

#include<bits/stdc++.h>
using namespace std;
int n;
string s;
struct node
{
    int son[27];
    int deep;
    int fa;
    int tap;
    char x;
}trie[500009];
int cnt;
int all;
int flag;
int king[500009];
int maxn=-1;
int maxs;
void insert(string s)
{
    int u=0;
    int len=s.size();
    for(int i=0;i<len;i++)
    {
        int c;
        c=s[i]-'a';
        if(!trie[u].son[c])
        {
            trie[u].son[c]=++cnt;
            all++;
            int t;
            t=trie[u].son[c];
            trie[t].deep=trie[u].deep+1;
            trie[t].fa=u;
        }
        u=trie[u].son[c]; 
    }
    king[u]=1;
    if(maxn<trie[u].deep)
    {
        maxn=trie[u].deep;
        maxs=u;
    }
//  cout<<u<<endl;
}
int ans;
void dfs(int u)
{
    if(king[u])
    {
        ans++;
        return;
    }
    for(int i=0;i<26;i++)
    {
        if(!trie[u].son[i]) continue;
//      cout<<"hello"<<endl;
        ans++;
        dfs(trie[u].son[i]);
        ans++;
    }
}
void tap()
{
    int now;
    now=maxs;
    while(now)
    {
//      cout<<now<<endl;
        trie[now].tap=1;
        now=trie[now].fa;
    }
}
void find(int u)
{
//  cout<<"hello"<<endl;
    for(int i=0;i<26;i++)
    {
        int v;
        v=trie[u].son[i];
//      cout<<v<<" "<<trie[v].tap<<endl;
        if(v&&trie[v].tap)
        {
//          cout<<v<<endl;
            trie[u].son[26]=v;
            trie[u].son[i]=0;
            trie[u].x=(char)(i+'a');
            find(v);
            break;
        }
    }
}
void dfsprint(int u)
{
    if(king[u])
    {
        cout<<'P'<<endl;
        return;
    }
    for(int i=0;i<=26;i++)
    {
        if(!trie[u].son[i]) continue;
        char x;
        if(i==26) cout<<trie[u].x<<endl;
        else 
        {
        x=i+'a';
        cout<<x<<endl;
        }
        flag++;
        dfsprint(trie[u].son[i]);
        if(flag==all) 
        {return;}
        cout<<'-'<<endl;
    }
}
int main()
{
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        cin>>s;
        insert(s);
    }
//  cout<<trie[1].son[(int)('o'-'a')]<<endl;
    dfs(0);
    flag=0;
//  cout<<trie[1].son[(int)('o'-'a')]<<endl;
    cout<<ans-maxn<<endl;
    tap();
    find(0);
    dfsprint(0); 
    return 0;
}

by Star_V @ 2023-07-29 15:52:39

未考虑字符串前缀情况,此帖结


by lsj2009 @ 2023-09-22 20:24:48

感谢提醒/bx


by VectorLi @ 2023-11-03 21:06:04

感谢,卡了一个小时了


|