POJ_2185_二维KMP

http://poj.org/problem?id=2185

 

求最小覆盖矩阵,把KMP扩展到二维,行一次,列一次,取最小覆盖线段相乘即可。

 

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;

int r,c;
char a1[10005][80] = {0},a2[80][10005] = {0};
int next1[10005],next2[80];

void get_next1()
{
    int i = 0,j = -1;
    next1[0] = -1;
    while(i < r)
    {
        if(j == -1 || !strcmp(a1[i],a1[j]))    next1[++i] = ++j;
        else    j = next1[j];
    }
}
void get_next2()
{
    int i = 0,j = -1;
    next2[0] = -1;
    while(i < c)
    {
        if(j == -1 || !strcmp(a2[i],a2[j]))    next2[++i] = ++j;
        else    j = next2[j];
    }
}

int main()
{
    int i,j;
    scanf("%d%d",&r,&c);
    for(int i = 0;i < r;i++)    scanf("%s",a1[i]);
    for(int i = 0;i < r;i++)
    {
        for(j = 0;j < c;j++)    a2[j][i] = a1[i][j];
    }
    get_next1();
    get_next2();
    printf("%d\n",(r-next1[r])*(c-next2[c]));
     
}

 

posted @ 2016-10-11 16:49  zzzzzzzzhu  阅读(199)  评论(0编辑  收藏  举报