Cod sursa(job #804696)

Utilizator ChallengeMurtaza Alexandru Challenge Data 30 octombrie 2012 09:24:52
Problema Aho-Corasick Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.72 kb
#include<stdio.h>
#include<cstring>

#define maxA 1000005
#define maxn 105
#define maxsir 10005

FILE*f=fopen("ahocorasick.in","r");
FILE*g=fopen("ahocorasick.out","w");

int n;
char A[maxA],sir[maxsir];

struct T{
	int nr;
	T *next;
	T *son[27];
	
	T () {
		nr = 0;
		next = NULL;
		for ( int i = 1 ; i < 27 ; ++i )	son[i] = NULL;
	}
};
T *R = new T;
T *where[maxn],*C[maxn*maxsir];

void insert ( T *nod , char *p , int ind ){
	int ch = (*p) - 'a' + 1;
	if ( !(ch >= 1 && ch <= 26) ){
		where[ind] = nod;
		return ;
	}
	
	if ( nod->son[ch] == NULL ){
		nod->son[ch] = new T;
	}
	insert(nod->son[ch],p+1,ind);
}

int main () {
	
	fscanf(f,"%s",A+1); int lung = strlen(A+1);
	fscanf(f,"%d\n",&n);
	for ( int i = 1 ; i <= n ; ++i ){
		fscanf(f,"%s",sir+1);
		insert(R,sir+1,i);
	}
	
	int p = 1,u = 0;	C[++u] = R;
	R->next = R;
	for ( ; p <= u ; ++p ){
		T *nod = C[p];
		
		for ( int ch = 1 ; ch <= 26 ; ++ch ){
			if ( nod->son[ch] == NULL )	continue ;
			
			T *suffix = nod->next;
			while ( suffix != R && suffix->son[ch] == NULL ){
				suffix = suffix->next;
			}
			if ( suffix->son[ch] != NULL && suffix->son[ch] != nod->son[ch] )
				nod->son[ch]->next = suffix->son[ch];
			else
				nod->son[ch]->next = R;
			
			C[++u] = nod->son[ch];
		}
	}
	
	T *nod = R;
	for ( int i = 1 ; i <= lung ; ++i ){
		int ch = A[i]-'a'+1;
		
		while ( nod != R && nod->son[ch] == NULL ){
			nod = nod->next; 
		}
		if ( nod->son[ch] != NULL ){
			nod = nod->son[ch];
		}
		++nod->nr;
	}
	
	for ( int i = u ; i >= 1 ; --i ){
		C[i]->next->nr += C[i]->nr;
	}
	
	for ( int i = 1 ; i <= n ; ++i ){
		fprintf(g,"%d\n",where[i]->nr);
	}
	
	fclose(f);
	fclose(g);
	
	return 0;
}