HDU 3065 病毒侵襲持續中

題目大意:中文

題目鏈接

註釋代碼:

無註釋代碼:

#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cctype>
#include <queue>

#define	AN	26

#define	MAXN	1000
#define	MAXM	50
#define	MAXT	2000000
#define	MAXS	50000

using namespace std;

struct	Node {

	int		out[AN];
	int		prv;
	int		type;
};

Node	stat[MAXS];
char	m[MAXN + 1][MAXM + 1];
char	t[MAXT + 1];
int     ans[MAXN + 1];
int		tsn;

void
insert( char *mm, int type ) {

	int		a;
	int		s;

	s = 1;
	while ( *mm ) {
	
		a = *mm++ - 'A';
		if ( !stat[s].out[a] ) {
		
			stat[s].out[a] = ++tsn;
			s = tsn;

			continue;
		}

		s = stat[s].out[a];
	}

	stat[s].type = type;
}

void
build(int n) {

	int		i;
	int		s, ss, r;
	int		a;
    
    queue<int>		q;

    memset(stat, 0, sizeof(stat));
	for ( a = 0; a < AN; a++ ) stat[0].out[a] = 1;
	tsn = 1;
	q.push(1);
	for ( i = 1; i <= n; i++ ) {

		scanf("%s", m[i]);
		insert( m[i], i );
	}

	while ( !q.empty() ) {
	
		s = q.front();
		q.pop();

		for ( a = 0; a < AN; a++ )
			if ( ss = stat[s].out[a] ) {
			
				q.push(ss);

				r = s;
				while ( true )
					if ( stat[ r = stat[r].prv ].out[a] ) {
					
						stat[ss].prv = stat[r].out[a];
						break;
					}
			}
	}
}

void
run( char *t, int n ) {

	int		s, r;
	int		a;
	int		i;
    
    memset(ans, 0, sizeof(ans));

	s = 1;
	while ( *t ) {
	
        if ( !isupper(*t) ) {
            
            s = 1;
            t++;
            continue;
        }
        
		a = *t++ - 'A';

		while ( !stat[s].out[a] ) s = stat[s].prv;
		if ( !s ) { s = 1; continue; }

		s = stat[s].out[a];
		r = s;
		while ( r != 1 ) {
		
            if ( stat[r].type ) ans[ stat[r].type ]++;
			r = stat[r].prv;
		}
	}
    
    for ( i = 1; i <= n; i++ )
        if ( ans[i] )
            printf("%s: %d\n", m[i], ans[i]);
}

int
main() {

	int		n;

    while ( ~scanf("%d", &n) ) {
        
        build(n);
        scanf("%s", t);
        run( t, n );
    }
	
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章