SW Expert Academy
SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!
swexpertacademy.com
시간 제한이 1초이므로
브루트포스로 비교를 하면 시간 초과가 난다.
라빈 카프 알고리즘을 이용한다.
<2차원 배열 해싱>
가로 해싱을 하고
세로 해싱을 해준다.
중요한 것은
해시값을 다르게 줘야한다!!
같게 주면 대칭 구조가 나올 수 있다.
은기의 그림을 해싱.
선생님의 그림을 해싱
2중 포문 돌려서 해시 값 비교로 끝내면 된다.
<소스 코드>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
|
#include <iostream>
using namespace std;
int mod = ((1 << 30) - 1);
int ePic[2001][2001];
int tPic[2001][2001];
int tmp[2001][2001];
int cmp_hash[2001][2001];
int Hashing(int* arr, int lim, int kugi)
{
int hash = 0;
for (int i = 0; i < lim; i++)
{
hash += (hash << kugi) + *arr;
arr++;
}
return (int) (hash & mod);
}
inline int Calc(int lim, int kugi)
{
int x = 1;
for (int i = 1; i < lim; i++)
x += (x << kugi);
return (int) (x & mod);
}
int T_Hashing(int prev_h, int minus, int hash_v, int add, int kugi)
{
int hash = prev_h - (minus * hash_v);
hash += (hash << kugi) + add;
return (int)(hash & mod);
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int test;
cin >> test;
for (int t = 1; t <= test; t++)
{
int h, w, n, m;
cin >> h >> w >> n >> m;
for (int i = 0; i < h; i++)
{
for (int j = 0; j < w; j++)
{
char c;
cin >> c;
if (c == 'o')
ePic[i][j] = 1;
else
ePic[i][j] = 0;
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
char c;
cin >> c;
if (c == 'o')
tPic[i][j] = 1;
else
tPic[i][j] = 0;
}
}
// 가로 해싱
for (int i = 0; i < h; i++)
{
tmp[0][i] = Hashing(ePic[i], w, 4);
}
// 세로 해싱
int myHash = Hashing(tmp[0], h, 5);
int garo = Calc(w, 4);
int sero = Calc(h, 5);
// 선생님 가로 해싱
for (int i = 0; i < n; i++)
{
tmp[0][i] = Hashing(tPic[i], w, 4);
// 하나 빼기
for (int j = 1; j < m - w + 1; j++)
{
tmp[j][i] = T_Hashing(tmp[j - 1][i], tPic[i][j - 1], garo, tPic[i][j + w - 1], 4);
}
}
// 선생님 세로 해싱
for (int i = 0; i < m - w + 1; i++)
{
cmp_hash[0][i] = Hashing(tmp[i], h, 5);
// 하나 빼기
for (int j = 1; j < n - h + 1; j++)
{
cmp_hash[j][i] = T_Hashing(cmp_hash[j - 1][i], tmp[i][j - 1], sero, tmp[i][j + h - 1], 5);
}
}
int ans = 0;
for (int i = 0; i < n - h + 1; i++)
{
for (int j = 0; j < m - w + 1; j++)
{
if (cmp_hash[i][j] == myHash)
ans++;
}
}
cout << '#'<< t << ' ' << ans << '\n';
}
return 0;
}
|
cs |
'해시' 카테고리의 다른 글
unordered_map 사용법 (0) | 2024.02.23 |
---|---|
단어미로 (0) | 2024.02.23 |
숫자조각게임 (0) | 2024.02.05 |
문자열 관리 프로그램 (0) | 2024.02.04 |
대칭 차집합 & 문자열 집합 (1) | 2023.10.24 |