BZOJ 2351 [BeiJing 2011] 字符串Hash 解题报告

来源:互联网 发布:ubuntu 22端口被拒绝 编辑:程序博客网 时间:2024/05/31 13:14

2351: [BeiJing2011]Matrix

Description

给定一个M行N列的01矩阵,以及Q个A行B列的01矩阵,你需要求出这Q个矩阵哪些在原矩阵中出现过。
所谓01矩阵,就是矩阵中所有元素不是0就是1。

Input

输入文件的第一行为M、N、A、B,参见题目描述。
接下来M行,每行N个字符,非0即1,描述原矩阵。
接下来一行为你要处理的询问数Q。
接下来Q个矩阵,一共Q*A行,每行B个字符,描述Q个01矩阵。

Output

你需要输出Q行,每行为0或者1,表示这个矩阵是否出现过,0表示没有出现过,1表示出现过。

Sample Input

3 3 2 2
111
000
111
3
11
00
11
11
00
11

Sample Output

1
0
1

HINT

对于100%的实际测试数据,M、N ≤ 1000,Q = 1000
对于40%的数据,A = 1。
对于80%的数据,A ≤ 10。
对于100%的数据,A ≤ 100。

【解题报告】
行列Hash,子矩阵就用前缀的思想减去缀余部分就可以了

代码如下:

/**************************************************************    Problem: 2351    User: onepointo    Language: C++    Result: Accepted    Time:2004 ms    Memory:15048 kb****************************************************************/#include<cstdio>  #include<cstring>  #include<algorithm>  using namespace std; #define N 1100  #define BASE1 10016957  #define BASE2 10016959  #define Mod 10100  struct abcd{      unsigned num;      int next;  }table[N*N];  int m,n,a,b,q;  unsigned int sum[N][N],power1[N],power2[N];  int hash_table[Mod],tot;void Hash(unsigned int x)  {      int pos=x%Mod;      table[++tot].num=x;      table[tot].next=hash_table[pos];      hash_table[pos]=tot;  }  bool Get_Hash(unsigned int x)  {      int pos=x%Mod;      for(int i=hash_table[pos];i;i=table[i].next)      if(table[i].num==x) return true;      return false;     }  int main()  {      scanf("%d%d%d%d",&m,&n,&a,&b);    for(int i=1;i<=m;++i)      for(int j=1;j<=n;++j) scanf("%1d",&sum[i][j]);      for(int i=1;i<=m;++i)      for(int j=1;j<=n;++j) sum[i][j]+=sum[i-1][j]*BASE1;      for(int i=1;i<=m;++i)      for(int j=1;j<=n;++j) sum[i][j]+=sum[i][j-1]*BASE2;      power1[0]=power2[0]=1;      for(int i=1;i<N;++i)     {        power1[i]=power1[i-1]*BASE1;          power2[i]=power2[i-1]*BASE2;    }    for(int i=a;i<=m;++i)      for(int j=b;j<=n;++j)      {          unsigned int temp=sum[i][j]                -sum[i-a][j]*power1[a]                  -sum[i][j-b]*power2[b]                  +sum[i-a][j-b]*power1[a]*power2[b];          Hash(temp);      }      for(scanf("%d",&q);q;--q)      {          for(int i=1;i<=a;++i)          for(int j=1;j<=b;++j) scanf("%1d",&sum[i][j]);          for(int i=1;i<=a;++i)          for(int j=1;j<=b;++j) sum[i][j]+=sum[i-1][j]*BASE1;          for(int i=1;i<=a;++i)          for(int j=1;j<=b;++j) sum[i][j]+=sum[i][j-1]*BASE2;          unsigned int temp=sum[a][b];          puts(Get_Hash(temp)?"1":"0");    }      return 0;}