Skip to content

Commit c6a4f0c

Browse files
authored
math, FFT, d&c
1 parent 9dffe47 commit c6a4f0c

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

HackerRank/Best spot.cpp

+74
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
//math, FFT, d&c
2+
//https://www.hackerrank.com/contests/w6/challenges/best-spot/editorial
3+
#include <stdio.h>
4+
#include <math.h>
5+
#include <vector>
6+
#include <complex>
7+
#define cpd complex<double>
8+
using namespace std;
9+
const double PI = acos(-1);
10+
int R, C, H, W;
11+
int sqx[501][501], sqy;
12+
void FFT(vector<cpd > &F, vector<cpd > &A, cpd w) {
13+
if (A.size() == 1) F = A;
14+
else {
15+
int n = A.size();
16+
vector<cpd > a[2], f[2];
17+
for (int i = 0; i < n; ++i) a[i & 1].push_back(A[i]);
18+
F.resize(n); n >>= 1;
19+
FFT(f[0], a[0], w*w); FFT(f[1], a[1], w*w);
20+
cpd x = 1;
21+
for (int i = 0; i < n; ++i) {
22+
cpd odd = f[1][i] * x;
23+
F[i] = f[0][i] + odd;
24+
F[i + n] = f[0][i] - odd;
25+
x *= w;
26+
}
27+
}
28+
}
29+
int main() {
30+
int i, j;
31+
int RC, p;
32+
for (scanf("%d%d", &R, &C), RC = R * C, p = 1; p < RC + RC; p += p);
33+
vector<cpd > h(p), ps(p);
34+
int ix = 0;
35+
for (i = 1; i <= R; ++i) {
36+
for (j = 1; j <= C; ++j,++ix) {
37+
scanf("%d",sqx[i]+j);
38+
h[ix] = h[ix + RC] = sqx[i][j];
39+
sqx[i][j] *= sqx[i][j];
40+
sqx[i][j] += sqx[i][j - 1] + sqx[i - 1][j] - sqx[i - 1][j - 1];
41+
}
42+
}
43+
for (scanf("%d%d", &H, &W), i = 1,ix=RC; i <= H; ++i,ix-=C) {
44+
for (j = 1; j <= W; ++j) {
45+
int height; scanf("%d",&height);
46+
ps[ix - j] = height;
47+
sqy += height * height;
48+
}
49+
}
50+
double theta = (PI + PI) / p;
51+
cpd w(cos(theta), sin(theta));
52+
FFT(h, h, w); FFT(ps, ps, w);
53+
for (i = 0; i < p; ++i) h[i] *= ps[i];
54+
w = {cos(-theta),sin(-theta)};
55+
FFT(h, h, w);
56+
int ans = -1;
57+
int r, c;
58+
for (i = 1,ix=RC-1; i <= R-H+1; ++i,ix+=C) {
59+
for (j = 1; j <= C-W+1; ++j) {
60+
double coef = h[ix+j-1].real()/p;
61+
coef += coef > 0 ? 0.5 : -0.5;
62+
int xy = coef;
63+
int sum = sqx[i + H-1][j + W-1]-sqx[i-1][j+W-1]
64+
-sqx[i+H-1][j-1]+sqx[i-1][j-1];
65+
sum += sqy - xy - xy;
66+
if (ans<0 || ans>sum) {
67+
ans = sum;
68+
r = i, c = j;
69+
}
70+
}
71+
}
72+
printf("%d\n%d %d",ans,r,c);
73+
return 0;
74+
}

0 commit comments

Comments
 (0)