bzoj3012 [Usaco2012 Dec]First! trie+拓扑排序

15 篇文章 0 订阅
14 篇文章 0 订阅

Description


给n个串,对于每个串输出是否存在一种字符的大小关系使得这个串是字典序最小的
总长<=3e5

Solution


首先如果串A是串B的前缀那么B肯定不会是最小的
要让一个串S字典序最小,也就是所有与S前缀相同的串T,S和T不同的第一个字符位i我们得钦定S[i]<T[i]
推到这个结论就很好做了,我们建trie,然后用单向边表示字母的大小关系,若出现了环说明肯定不合法

Code


#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <vector>
#include <queue>

#define rep(i,st,ed) for (int i=st;i<=ed;++i)
#define fill(x,t) memset(x,t,sizeof(x))

const int N=500010;

struct edge {int y,next;} e[N];

int rec[N][26],st[N],len[N],tot;
int d[55],ls[55],edCnt;

char str[N];

bool vis[N],wjp[55][55];

void add_edge(int x,int y) {
	e[++edCnt]=(edge) {y,ls[x]}; ls[x]=edCnt;
}

bool check(int id) {
	fill(d,0);
	fill(ls,0);
	fill(wjp,0);
	edCnt=0; int x=0;
	rep(i,st[id],st[id]+len[id]-1) {
		int tar=str[i]-'a';
		if (vis[x]) return 0;
		rep(j,0,25) if (rec[x][j]&&j!=tar&&!wjp[tar][j]) {
			wjp[tar][j]=1;
			add_edge(tar,j); d[j]++;
		}
		x=rec[x][tar];
	}
	std:: queue <int> que;
	rep(i,0,25) if (!d[i]) {
		que.push(i);
	}
	for (;!que.empty();) {
		int x=que.front(); que.pop();
		for (int i=ls[x];i;i=e[i].next) {
			if (!(--d[e[i].y])) que.push(e[i].y);
		}
	}
	rep(i,0,25) if (d[i]) return 0;
	return 1;
}

int main(void) {
	int n; scanf("%d",&n); getchar();
	rep(i,1,n) {
		st[i]=st[i-1]+len[i-1]; int x=0;
		for (char ch=getchar();ch!='\n';ch=getchar()) {
			str[st[i]+len[i]]=ch; len[i]++;
			if (!rec[x][ch-'a']) rec[x][ch-'a']=++tot;
			x=rec[x][ch-'a'];
		}
		vis[x]=1;
	}
	std:: vector <int> prt;
	rep(i,1,n) if (check(i)) prt.push_back(i);
	printf("%d\n", prt.size());
	for (int i=0;i<prt.size();++i) {
		rep(j,st[prt[i]],st[prt[i]]+len[prt[i]]-1) {
			putchar(str[j]);
		} putchar('\n');
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值