bzoj 1195 [HNOI2006]最短母串

1195: [HNOI2006]最短母串

Time Limit: 10 Sec   Memory Limit: 32 MB
Submit: 1467   Solved: 488
[ Submit][ Status][ Discuss]

Description

给定n个字符串(S1,S2,„,Sn),要求找到一个最短的字符串T,使得这n个字符串(S1,S2,„,Sn)都是T的子串。

Input

第一行是一个正整数n(n<=12),表示给定的字符串的个数。以下的n行,每行有一个全由大写字母组成的字符串。每个字符串的长度不超过50.

Output

只有一行,为找到的最短的字符串T。在保证最短的前提下,如果有多个字符串都满足要求,那么必须输出按字典序排列的第一个。

Sample Input

2
ABCD
BCDABC

Sample Output

ABCDABC

HINT

Source




【分析】

类似分层图BFS...

早上的确不适合写题...数组开小调了TM一个小时

评测姬说我RE会怎样哦,为啥数组开小老是WA QAQ



【代码】

//bzoj 1195 
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
#define ll long long
#define mp make_pair
#define M(a) memset(a,0,sizeof a)
#define fo(i,j,k) for(i=j;i<=k;i++)
using namespace std;
const int mxn=605;
char s[mxn];
int n,m,num,top;
bool vis[mxn][1<<12];
int pre[mxn][1<<12][2],self[mxn],st[mxn];
queue <int> Q;
queue < pair<int,int> > q;
struct node {int cnt,fail,son[30];} a[mxn]; 
inline void trie(int w)
{
	scanf("%s",s+1);
	int i,j,x=0,len=strlen(s+1);
	fo(i,1,len)
	{
		int c=s[i]-'A'+1;
		if(!a[x].son[c])
		  a[x].son[c]=(++num);
		x=a[x].son[c];
	}
	a[x].cnt|=(1<<w-1);
}
inline void build()
{
	int i,j,T=0;
	fo(i,1,26) if(a[0].son[i]) Q.push(a[0].son[i]);
	while(!Q.empty())
	{
		int x=Q.front();Q.pop();
		int fail=a[x].fail;
		fo(i,1,26)
		{
			int y=a[x].son[i];
			if(y) Q.push(y),a[y].fail=a[fail].son[i];
			else a[x].son[i]=a[fail].son[i];
		}
		a[x].cnt|=a[fail].cnt;
	}
}
inline void print(int x,int step)
{
	st[++top]=self[x];
	while(pre[x][step][0])
	{
		int y=pre[x][step][0],now=pre[x][step][1];
		x=y,step=now;
		st[++top]=self[x];
	}
	for(int i=top;i;i--) if(st[i]) printf("%c",st[i]+'A'-1);
}
inline void bfs()
{
	int i,end=(1<<n)-1;
	q.push(mp(0,0)),vis[0][0]=1;
	while(!q.empty())
	{
		int x=q.front().first,now=q.front().second;
		q.pop();
		fo(i,1,26)
		{
			int y=a[x].son[i];
			int tmp=now|a[y].cnt;
			if(!vis[y][tmp])
			{
				q.push(mp(y,tmp)),vis[y][tmp]=1;
				pre[y][tmp][0]=x,pre[y][tmp][1]=now,self[y]=i;
				if(tmp==end)
				{
					print(y,tmp);
					return;
				}
			}
		}
	}
}
int main()
{
	int i,j;
	scanf("%d",&n);
	fo(i,1,n) trie(i);
	build();
//	printf("num=%d\n",num);
	bfs();
	return 0;
}
/*
6
AAA
AAB
AAC
AAD
AAE
AAF
*/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值