bzoj3012 [Usaco2012 Dec]First! trie + Topological Sorting

Description

Given n n strings, there is a relationship between the size of each string output so that the string is lexicographically minimum
Chief <=3e5

Solution

First, if string A is the prefix of string B, then B is certainly not the smallest.
To minimize the lexicographic order of a string S, i.e. all strings with the same S prefix T, S and T with different first character bits i, we have to specify S [i] < T [i]
It's good to draw this conclusion. Let's construct trie, and then use one-way side to express the size of letters. If there is a ring, it must be illegal.

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;
}

Posted by peterg012 on Sun, 07 Apr 2019 20:39:31 -0700