KMP算法,oj2087,Oulipo

對於一些簡單的查找我們可以用c庫函數strstr

 

#include <stdio.h>
#include <string.h>

typedef char* Position;
#define NotFound NULL

int main()
{
	char string[] = "This is a simple example.";
	char pattern[] = "simple";
	Position p = strstr( string, pattern );
	if ( p == NotFound ) printf("Not Found.\n");
	else printf("%s\n", p);
	return 0;
}

但是時間複雜度太高

因此我們需要去學習KMP算法,時間複雜度爲O (n + m )

用kmp算法最重要的就是求next值

具體求法我傳到了資源庫,有時間的話會過來完善下

 

pattern

A

B

C

A

B

C

A

C

A

B

J

0

1

2

3

4

5

6

7

8

9

next

-1

-1

-1

0

1

2

3

-1

0

1

 

下面是具體的代碼實現

#include <stdio.h>
#include <string.h> 
#include <stdlib.h>
 //match 相當於next
typedef int Position;
#define NotFound -1
 
void BuildMatch( char *pattern, int *match )
{
    Position i, j;
    int m = strlen(pattern);
    match[0] = -1;
     
    for ( j=1; j<m; j++ ) {
        i = match[j-1];
        while ( (i>=0) && (pattern[i+1]!=pattern[j]) )//不匹配時,回退
            i = match[i];
        if ( pattern[i+1]==pattern[j] ) // 後面的匹配上了
             match[j] = i+1;
        else match[j] = -1;
    }
}
 
Position KMP( char *string, char *pattern )
{
    int n = strlen(string);     // O(n)
    int m = strlen(pattern);    // O(m)
    Position s, p, *match;
     
    if ( n < m ) return NotFound;
    match = (Position *)malloc(sizeof(Position) * m);
    BuildMatch(pattern, match);
    s = p = 0;
    while ( s<n && p<m ) {      //O(n)
        if ( string[s]==pattern[p] ) {      //匹配到了
            s++; p++;
        }
        else if (p>0) p = match[p-1]+1;     //前面匹配不到的時候,回溯到[p-1]+1
        else s++;     //一開始就不匹配
    }
    return ( p==m )? (s-m) : NotFound;
}
 
int main()
{
    char string[] = "This is a simple example.";
    char pattern[] = "simple";
    Position p = KMP(string, pattern);
    if (p==NotFound) printf("Not Found.\n");
    else printf("%s\n", string+p);
    return 0;  
}

下面是一些OJ題的應用

2087剪花布條

Problem Description

一塊花布條,裏面有些圖案,另有一塊直接可用的小飾條,裏面也有一些圖案。對於給定的花布條和小飾條,計算一下能從花布條中儘可能剪出幾塊小飾條來呢?

 

 

Input

輸入中含有一些數據,分別是成對出現的花布條和小飾條,其布條都是用可見ASCII字符表示的,可見的ASCII字符有多少個,布條的花紋也有多少種花樣。花紋條和小飾條不會超過1000個字符長。如果遇見#字符,則不再進行工作。

 

 

Output

輸出能從花紋布中剪出的最多小飾條個數,如果一塊都沒有,那就老老實實輸出0,每個結果之間應換行。

 

 

Sample Input


 

abcde a3

aaaaaa aa

#

 

 

Sample Output


 

0 3

#include <stdio.h>

const int maxn = 10005;
int next[maxn];

void get_next( char * s );
int kmp( char *string, char *pattern );

int main()
{
    char string[10005], pattern[10005];
    while(1) {
        scanf("%s", &*string);
        if ( string[0] == '#' && !string[1] ) break;
        scanf("%s", &*pattern);
        printf("%d\n",kmp(string,pattern));
    }
    return 0;
}

void get_next( char *s )
{
    int i = 0, j = -1;
    next[0] = -1;
    while ( s[i] ) {
        if ( j== -1 || s[i] == s[j] )
            next[++i] = ++j;
        else
            j = next[j];
    }
}

int kmp( char *string, char *pattern )
{
    int answers = 0;
    get_next( pattern );
    int i = 0, j = 0;
    while ( string[i] ) {
        if ( j == -1 || string[i] == pattern[j] ) {
            i++,j++;
            if ( !pattern[j] ) {
                answers++;
                j = 0;
            }
        }
        else j = next[j];
    }
    return answers;
}

Oulipo

Problem Description

The French author Georges Perec (1936–1982) once wrote a book, La disparition, without the letter 'e'. He was a member of the Oulipo group. A quote from the book:

Tout avait Pair normal, mais tout s’affirmait faux. Tout avait Fair normal, d’abord, puis surgissait l’inhumain, l’affolant. Il aurait voulu savoir où s’articulait l’association qui l’unissait au roman : stir son tapis, assaillant à tout instant son imagination, l’intuition d’un tabou, la vision d’un mal obscur, d’un quoi vacant, d’un non-dit : la vision, l’avision d’un oubli commandant tout, où s’abolissait la raison : tout avait l’air normal mais…

Perec would probably have scored high (or rather, low) in the following contest. People are asked to write a perhaps even meaningful text on some subject with as few occurrences of a given “word” as possible. Our task is to provide the jury with a program that counts these occurrences, in order to obtain a ranking of the competitors. These competitors often write very long texts with nonsense meaning; a sequence of 500,000 consecutive 'T's is not unusual. And they never use spaces.

So we want to quickly find out how often a word, i.e., a given string, occurs in a text. More formally: given the alphabet {'A', 'B', 'C', …, 'Z'} and two finite strings over that alphabet, a word W and a text T, count the number of occurrences of W in T. All the consecutive characters of W must exactly match consecutive characters of T. Occurrences may overlap.
 

 

 

Input

The first line of the input file contains a single number: the number of test cases to follow. Each test case has the following format:

One line with the word W, a string over {'A', 'B', 'C', …, 'Z'}, with 1 ≤ |W| ≤ 10,000 (here |W| denotes the length of the string W).
One line with the text T, a string over {'A', 'B', 'C', …, 'Z'}, with |W| ≤ |T| ≤ 1,000,000.

 

 

Output

For every test case in the input file, the output should contain a single number, on a single line: the number of occurrences of the word W in the text T.
 

 

 

Sample Input


 

3

BAPC

BAPC

AZA

AZAZAZA

VERDI

AVERDXIVYERDIAN

 

 

Sample Output


 

1 3 0

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

const int maxn = 10005;
int next[maxn];
int cnt;
char string[10005], pattern[10005];

void get_next( int len2 );
int kmp(int len1, int len2 );

int main()
{
	int num, len1, len2;
	scanf("%d",&num);
	getchar();
	while ( num-- ) {
		gets(pattern);
		gets(string);
		len1 = strlen(string);
		len2 = strlen(pattern);
		cnt = 0;
		kmp(len1,len2);
		printf("%d\n",cnt);
	}
	return 0;
}

void get_next( int len2 )
{
	int i = 0, j = -1;
	next[0] = -1;
	while ( i < len2 ) {
		if ( j == -1 || pattern[i] == pattern[j] )
			next[++i] = ++j;
		else
			j = next[j];
	}
}

int kmp( int len1, int len2 )
{
	int i = 0, j = 0;
	get_next(len2);
	while ( i < len1 ) {
		if ( j == -1 || string[i] == pattern[j] ) {
			++i,++j;
		}
		else
			j = next[j];
		if ( j == len2 ) {
			cnt++;
			j = next[j];
		}
	}
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章