1. 程式人生 > >外星聯絡[trie樹]

外星聯絡[trie樹]

傳送門

每個點先後建trie樹 , 然後先dfs "0" 兒子 , 再dfs"1" 兒子 , 這樣對應字典序

如果cnt<=1 直接return , 因為後面的也都不可能>1了


#include<bits/stdc++.h>
#define N 3050
using namespace std;
char s[N]; int n,tot=1,t[N*N][2],cnt[N*N];
void build(int st){
	int now=1; 
	for(int i=st;i<=n;i++){
		int ch=s[i]-'0' , &res=t[now][ch];
		if(!res) res = ++tot; 
		cnt[res]++ , now = res;
	}
}
void dfs(int u){
	if(cnt[u]<=1) return;
	printf("%d\n",cnt[u]);
	dfs(t[u][0]) , dfs(t[u][1]);
}
int main(){
	scanf("%d%s",&n,s+1);
	for(int i=1;i<=n;i++) build(i);
	dfs(t[1][0]) , dfs(t[1][1]); return 0;
}