首页 > 代码库 > POJ 3690 Constellations (哈希)

POJ 3690 Constellations (哈希)

题意:给定上一n*m的矩阵,然后的t个p*q的小矩阵,问你匹配不上的有多少个。

析:可以直接用哈希,也可以用AC自动机解决。

代码如下:

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <cstdio>
#include <string>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <cstring>
#include <set>
#include <queue>
#include <algorithm>
#include <vector>
#include <map>
#include <cctype>
#include <cmath>
#include <stack>
#include <sstream>
#define debug() puts("++++");
#define gcd(a, b) __gcd(a, b)
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define freopenr freopen("in.txt", "r", stdin)
#define freopenw freopen("out.txt", "w", stdout)
using namespace std;

typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> P;
const int INF = 0x3f3f3f3f;
const LL LNF = 1e16;
const double inf = 0x3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double eps = 1e-8;
const int maxn = 1000 + 10;
const int mod = 1e9 + 7;
const int dr[] = {-1, 0, 1, 0};
const int dc[] = {0, 1, 0, -1};
const char *de[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"};
int n, m;
const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
inline bool is_in(int r, int c){
  return r >= 0 && r < n && c >= 0 && c < m;
}
int p, q;
const ULL B1 = 123;
const ULL B2 = 9973;
char s[maxn][maxn], ch[maxn][maxn];
ULL Hash[maxn][maxn], tmp[maxn][maxn];
ULL t1, t2;

void solve(char s[][maxn], int n, int m){
  for(int i = 0; i < n; ++i){
    ULL e = 0;
    for(int j = 0; j < q; ++j)  e = e * B1 + s[i][j];
    for(int j = 0; j + q <= m; ++j){
      tmp[i][j] = e;
      if(j + q < m)  e = e * B1 - t1 * s[i][j] + s[i][j+q];
    }
  }

  for(int j = 0; j + q <= m; ++j){
    ULL e = 0;
    for(int i = 0; i < p; ++i)  e = e * B2 + tmp[i][j];
    for(int i = 0; i + p <= n; ++i){
      Hash[i][j] = e;
      if(i + p < n)  e = e * B2 - t2 * tmp[i][j] + tmp[i+p][j];
    }
  }
}

int main(){
  int t, kase = 0;
  while(scanf("%d %d %d %d %d", &n, &m, &t, &p, &q) == 5 && n+m+p+q+t){
    for(int i = 0; i < n; ++i)  scanf("%s", s+i);
    multiset<ULL> sets;
    t1 = t2 = 1;
    for(int i = 0; i < q; ++i)  t1 *= B1;
    for(int i = 0; i < p; ++i)  t2 *= B2;
    for(int i = 0; i < t; ++i){
      for(int j = 0; j < p; ++j)
        scanf("%s", ch+j);
      solve(ch, p, q);
      sets.insert(Hash[0][0]);
    }
    solve(s, n, m);
    for(int i = 0; i + p <= n; ++i)
      for(int j = 0; j + q <= m; ++j)
        sets.erase(Hash[i][j]);
    printf("Case %d: %d\n", ++kase, t-(int)sets.size());
  }
  return 0;
}

  

POJ 3690 Constellations (哈希)