【牛客】假的字符串

本文详细解析了一道NOIP算法题,通过构建Trie树和使用拓扑排序来判断字符串间的字典序关系,从而找出可能成为字典序最小的字符串集合。文章提供了完整的代码实现和思路说明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

链接:https://ac.nowcoder.com/acm/contest/907/E
Description
给定n个字符串,互不相等,你可以任意指定字符之间的大小关系(即重定义字典序),求有多少个串可能成为字典序最小的串,并输出它们

Input
第一行一个数表示n
之后n行每行一个字符串表示给定的字符串
Output:
第一行输出一个数x表示可行的字符串个数
之后输出x行,每行输出一个可行的字符串
输出的顺序和输入的顺序一致
SampleInput
6
mcfx
ak
ioi
wen
l
a
SampleOutput
5
mcfx
ioi
wen
l
a
Tips
对于100%的数据,
n <= 30000 , 字符串总长<= 300000
字符集为小写字符
Solution
Trie树判断前缀, 拓扑排序判环

#include <bits/stdc++.h>
 
using namespace std;
 
int trie[300010][26], tot = 1;
bool End[300010];
string s[30010];
int ans[30010], cnt = 0;
int n;
int edge[30][30], deg[30];

bool top_sort()
{
    int res(0);
    queue<int> q;
    for (int i = 0; i < 26; i++)
        if (deg[i] == 0) q.push(i), res |= (1 << i);
    while (q.size())
    {
        int x = q.front(); q.pop();
        for (int i = 0; i < 26; i++)
            if (edge[x][i])
            	if (--deg[i] == 0)
            		q.push(i), res |= (1 << i);
    }
    return res == ((1 << 26) - 1);
}

void insert(const string &a)
{
    int p = 1;
    for (int i = 0; i < a.size(); i++)
    {
        int ch = a[i] - 'a';
        if (trie[p][ch] == 0) trie[p][ch] = ++tot;
        p = trie[p][ch];
    }
    End[p] = true;
}
 
bool search(const string &a)
{
    memset(edge, 0, sizeof edge);
    memset(deg, 0, sizeof deg);
    int p = 1;
    for (int i = 0; i < a.size(); i++)
    {
        if (End[p]) return false;
        for (int j = 0; j < 26; j++)
            if (trie[p][j] && j != a[i] - 'a' && edge[a[i] - 'a'][j] == 0)
                edge[a[i] - 'a'][j] = 1, deg[j]++;
        p = trie[p][a[i] - 'a'];
    }
    return top_sort();
}
 
int main()
{
    ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
    cin >> n;
     
    for (int i = 1; i <= n; i++)
    {
        cin >> s[i];
        insert(s[i]);
    }
    for (int i = 1; i <= n; i++)
        if (search(s[i]))
            ans[++cnt] = i;
    cout << cnt << '\n';
    for (int i = 1; i <= cnt; i++)
        cout << s[ans[i]] << '\n';
     
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值