牛客竞赛NC15049 假的字符串 (字典树 + 拓扑排序判环)

 如何判断一个字符串无法作为字典序最小?

1.前缀出现

2.大小矛盾(出现环)

解决1.用字典树来存,先存再输出,记录单词结束位置,输出时判断前面的字母是否有为其他单词的结束

解决2.用拓扑排序判断环

代码:

#include<bits/stdc++.h>
using namespace std;
const int MAXN = 3e5 + 10;
struct node{
    char c;
    bool end;
    node* right;
    node* nex;
}p[MAXN];

int ptop = 1;
bool able[30001];

node* find(char c,node* pp)
{
    if(pp -> nex == NULL)
    {
        pp -> nex = &p[ptop];
        p[ptop++].c = c;
        return pp -> nex;
    }
    pp = pp -> nex;
    node* ppp;
    while(pp != NULL)
    {
        if(pp -> c == c)
            return pp;
        ppp = pp;
        pp = pp -> right;
    }
    ppp -> right = &p[ptop];
    p[ptop++].c = c;
    return ppp -> right;
}

void add(string str)
{
    int end = str.size();
    node* pp = &p[0];
    for(int i = 0;i < end;i++)
    {
        pp = find(str[i],pp);
    }
    pp -> end = true;
}
int main()
{
    int n;cin >> n;
    string st[30001];
    for(int i = 1;i <= n;i++)
    {
        string str;cin >> st[i];
        add(st[i]);
    }
    int sum = 0;
    for(int i = 1;i <= n;i++)
    {
        int end = st[i].size();
        node* pp,*ppp = p[0].nex;
        vector<int> a[26];
        int num[26] = {0};
        bool flag = true;
        for(int j = 0;j < end;j++)
        {
        	pp = ppp;
        	while(pp != NULL)
        	{
	        	if(pp -> c != st[i][j])
	            {
	                a[st[i][j] - 'a'].push_back(pp -> c - 'a');
	                num[pp -> c - 'a']++;
	            }
	            else
	            {
	                if(j != end - 1 && pp -> end == true)
	                    flag = false;
	                ppp = pp -> nex;
	            }
	            pp = pp -> right;
			}
        }
        queue<int> qu;
        for(int i = 0;i < 26;i++)
        {
            if(num[i] == 0)
                qu.push(i);
        }
        while(!qu.empty())
        {
            int x = qu.front();qu.pop();
            int end = a[x].size();
            for(int i = 0;i < end;i++)
            {
                num[a[x][i]]--;
                if(num[a[x][i]] == 0)
                    qu.push(a[x][i]);
            }
        }
        for(int i = 0;i < 26;i++)
        {
            if(num[i] != 0)
                flag = false;
        }
        if(flag)
            able[i] = 1,sum++;
    }
    cout << sum << endl;
    for(int i = 1;i <= n;i++)
    {
        if(able[i])
            cout << st[i] << endl;
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值