POJ 2185 Milking Grid(KMP)

来源:互联网 发布:ubuntu pip3 国内镜像 编辑:程序博客网 时间:2024/05/12 05:23

解题思路:

算是一个多维的KMP,其实是一样的,不过把1个字符的比较改成一行或一列字符的比较,对行和列使用两次KMP,最后乘起来就可以了。

#include <iostream>#include <cstring>#include <cstdlib>#include <cstdio>#include <algorithm>#include <cmath>#include <vector>#include <queue>#include <stack>#define LL long long#define FOR(i,x,y) for(int i=x;i<=y;i++)using namespace std;const int maxn = 10000 + 10;char s[maxn][100];int rnext[maxn];int cnext[maxn];int R, C;bool rsame(int x, int y){    for(int i=0;i<C;i++)    {        if(s[x][i] != s[y][i])            return 0;    }    return 1;}bool csame(int x, int y){    for(int i=0;i<R;i++)    {        if(s[i][x] != s[i][y])            return 0;    }    return 1;}int main(){    while(scanf("%d%d", &R, &C)!=EOF)    {        for(int i=0;i<R;i++)            scanf("%s", s[i]);        rnext[0] = 0, rnext[1] = 0;        for(int i=1;i<C;i++)        {            int j = rnext[i];            while(j && !csame(i,j)) j = rnext[j];            rnext[i+1] = (csame(i,j)) ? j + 1 : 0;        }        /*for(int i=0;i<=C;i++)            printf("%d ", rnext[i]);        printf("\n");*/        cnext[0] = 0, cnext[1] = 0;        for(int i=1;i<R;i++)        {            int j = cnext[i];            while(j && !rsame(i, j)) j = cnext[j];            cnext[i+1] = (rsame(i, j)) ? j + 1 : 0;        }        /*for(int i=0;i<=R;i++)            printf("%d ", cnext[i]);        printf("\n");*/        printf("%d\n", (R - cnext[R]) * (C - rnext[C]));    }}

0 0
原创粉丝点击