Best spot
Problem Statement :
In Chile, land are partitioned into a one large grid, where each element represents a land of size 1x1. Shaka is a newcomer in Chile and is trying to start his own business. He is planning to build a store. He has his own ideas for the "perfect store" which can be represented by a HxW grid. Element at position (i, j) represents height of land at index (i, j) in the grid. Shaka has purchased a land area which can be represented RxC grid (H <= R, W <= C). Shaka is interested in finding best HxW sub-grid in the acquired land. In order to compare the possible sub-grids, Shaka will be using the sum of squared difference between each cell of his "perfect store" and it's corresponding cell in the subgrid. Amongst all possible sub-grids, he will choose the one with smallest such sum. Note The grids are 1-indexed and rows increase from top to bottom and columns increase from left to right. If x is the height of a cell in the "perfect store" and y is the height of the corresponding cell in a sub-grid of the acquired land, then the squared difference is defined as (x-y)2 Input Format The first line of the input consists of two integers, R C, separated by single space. Then R lines follow, each one containing C space separated integers, which describe the height of each land spot of the purchased land. The next line contains two integers, H W, separated by a single space, followed by H lines with W space separated integers, which describes the "perfect store". Constraints 1 <= R, C <= 500 1 <= H <= R 1 <= W <= C No height will have an absolute value greater than 20. Output Format In the first line, output the smallest possible sum (as defined above) Shaka can find on exploring all the sub-grids (of size HxW) in the purchased land. In second line, output two space separated integers, i j, which represents the index of top left corner of sub-grid (on the acquired land) with the minimal such sum. If there are multiple sub-grids with minimal sum, output the one with the smaller row index. If there are still multiple sub-grids with minimal sum, output the one with smaller column index.
Solution :
Solution in C :
In C++ :
/*
*/
//#pragma comment(linker, "/STACK:16777216")
#include <fstream>
#include <iostream>
#include <string>
#include <complex>
#include <math.h>
#include <set>
#include <vector>
#include <map>
#include <queue>
#include <stdio.h>
#include <stack>
#include <algorithm>
#include <list>
#include <ctime>
#include <memory.h>
#define y0 sdkfaslhagaklsldk
#define y1 aasdfasdfasdf
#define yn askfhwqriuperikldjk
#define j1 assdgsdgasghsf
#define tm sdfjahlfasfh
#define lr asgasgash
#define eps 1e-14
//#define M_PI 3.141592653589793
#define bs 1000000007
#define bsize 256
#define N 120000
using namespace std;
typedef complex<double> base;
long s1;
vector< long > v1,v2,v3;
long r,c,ar[600][600];
long h,w,ex[600][600];
long s2;
long s[600][600];
long ans,ti,tj,ai,aj;
int rev (int num, int lg_n) {
int res = 0;
for (int i=0; i<lg_n; ++i)
if (num & (1<<i))
res |= 1<<(lg_n-1-i);
return res;
}
void fft (vector<base> & a, bool invert) {
int n = (int) a.size();
int lg_n = 0;
while ((1 << lg_n) < n) ++lg_n;
for (int i=0; i<n; ++i)
if (i < rev(i,lg_n))
swap (a[i], a[rev(i,lg_n)]);
for (int len=2; len<=n; len<<=1) {
double ang = 2*M_PI/len * (invert ? -1 : 1);
base wlen (cos(ang), sin(ang));
for (int i=0; i<n; i+=len) {
base w (1);
for (int j=0; j<len/2; ++j) {
base u = a[i+j], v = a[i+j+len/2] * w;
a[i+j] = u + v;
a[i+j+len/2] = u - v;
w *= wlen;
}
}
}
if (invert)
for (int i=0; i<n; ++i)
a[i] /= n;
}
void mult(vector<long > &a, vector<long> &b, vector<long> &c)
{
vector<base> fa,fb;
fa.resize(a.size());fb.resize(b.size());
for (int i=0;i<a.size();i++)
fa[i]=a[i];
for (int i=0;i<b.size();i++)
fb[i]=b[i];
long n=1;
while (n<max(a.size(),b.size()))n*=2;
n*=2;
fa.resize(n);fb.resize(n);
fft(fa,0);fft(fb,0);
for (int i=0;i<n;i++)
fa[i]*=fb[i];
fft(fa,n);
c.resize(n);
for (int i=0;i<n;i++)
c[i]=fa[i].real()+0.5;
}
int main(){
//freopen("magic.in","r",stdin);
//freopen("magic.out","w",stdout);
//freopen("C:/input.txt","r",stdin);
//freopen("C:/output.txt","w",stdout);
ios_base::sync_with_stdio(0);
//cin.tie(0);
cin>>r>>c;
for (int i=1;i<=r;i++)
for (int j=1;j<=c;j++)
cin>>ar[i][j];
cin>>h>>w;
for (int i=1;i<=h;i++)
for (int j=1;j<=w;j++)
{ cin>>ex[r-i+1][c-j+1];
s2+=ex[r-i+1][c-j+1]*ex[r-i+1][c-j+1];
}
for (int i=1;i<=r;i++)
for (int j=1;j<=c;j++)
{
s[i][j]=s[i-1][j]+s[i][j-1]-s[i-1][j-1]+ar[i][j]*ar[i][j];
}
for (int i=1;i<=r;i++)
for (int j=1;j<=c;j++)
{
v1.push_back(ar[i][j]);
}
for (int i=1;i<=r;i++)
for (int j=1;j<=c;j++)
v2.push_back(ex[i][j]);
mult(v1,v2,v3);
ans=2e9;
for (int i=r*c-1;i<r*c*2;i++)
{
ti=(i-r*c+1)/c+1;
tj=(i-r*c+1)%c+1;
if (ti+h>r+1)continue;
if (tj+w>c+1)continue;
s1=-2*v3[i];
s1+=s2;
s1+=s[ti+h-1][tj+w-1]-s[ti-1][tj+w-1]-s[ti+h-1][tj-1]+s[ti-1][tj-1];
if (s1<ans)
{
ans=s1;
ai=ti;
aj=tj;
}
}
cout<<ans<<endl;
cout<<ai<<" "<<aj<<endl;
cin.get();cin.get();
return 0;}
In Java :
import java.io.*;
import java.util.*;
public class Solution {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
static final int MOD = (11 << 19) + 1;
static final int ROOT = 177147; // 2^19-th root of 1 modulo MOD
static final int MAXN = 1 << 19;
int[] buildRevOrder() {
int[] res = new int[N];
int highBit = N >> 1;
for (int i = 0; i < N; i++) {
res[i] = res[i >> 1] >> 1;
if ((i & 1) == 1) {
res[i] |= highBit;
}
}
return res;
}
// int n;
int N;
int halfN;
int[] p; // len = N + 1
int[] powSimple; // len = halfN
int[] powInv;
int[] fft(int[] a, boolean inv) {
int[] pow = inv ? powInv : powSimple;
for (int i = 0; i < N; i++)
if (i < p[i]) {
int tmp = a[i];
a[i] = a[p[i]];
a[p[i]] = tmp;
}
for (int len = 2, half = 1, step = halfN; len <= N; len <<= 1, half <<= 1, step >>= 1) {
for (int st = 0; st < N; st += len) {
for (int i1 = st, i2 = st + half, j = 0; j < halfN; i1++, i2++, j += step) {
int u = a[i1];
int v = (int) ((long) a[i2] * pow[j] % MOD);
a[i1] = u + v;
if (a[i1] >= MOD) {
a[i1] -= MOD;
}
a[i2] = u - v;
if (a[i2] < 0) {
a[i2] += MOD;
}
}
}
}
if (inv) {
for (int i = 0; i < N; i++) {
a[i] = (int) ((long) a[i] * invN % MOD);
}
}
return a;
}
int invN;
static int pow(int a, int b) {
int res = 1;
while (b != 0) {
if ((b & 1) == 1)
res = (int) ((long) res * a % MOD);
a = (int) ((long) a * a % MOD);
b >>= 1;
}
return res;
}
static int getGoodN(int sz) {
int res = Integer.highestOneBit(sz);
return res == sz ? res << 1 : res << 2;
}
void prepareFFT(int N) {
this.N = N;
halfN = N >> 1;
powSimple = new int[halfN];
powInv = new int[halfN];
int mult = ROOT;
for (int i = N; i < MAXN; i <<= 1)
mult = (int) ((long) mult * mult % MOD);
powSimple[0] = powInv[0] = 1;
for (int i = 1, j = halfN - 1; i < halfN; i++, j--) {
powSimple[i] = (int) ((long) powSimple[i - 1] * mult % MOD);
powInv[j] = MOD - powSimple[i];
}
invN = pow(N, MOD - 2);
p = buildRevOrder();
}
int fix(int x) {
if (x < 0) {
x += MOD;
}
return x;
}
void solve() throws IOException {
int r = nextInt();
int c = nextInt();
int[] a = new int[r * c];
int[][] a2D = new int[r][c];
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++) {
a2D[i][j] = nextInt();
a[i * c + j] = fix(a2D[i][j]);
}
int h = nextInt();
int w = nextInt();
int[] b = new int[(h - 1) * c + w];
int sumBSq = 0;
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
int x = nextInt();
sumBSq += x * x;
b[i * c + j] = fix(x);
}
}
reverse(b);
prepareFFT(getGoodN(a.length));
int[] A = Arrays.copyOf(a, N);
int[] B = Arrays.copyOf(b, N);
A = fft(A, false);
B = fft(B, false);
for (int i = 0; i < N; i++) {
A[i] = (int) ((long) A[i] * B[i] % MOD);
}
int[] res = fft(A, true);
int[][] sum = new int[r + 1][c + 1];
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++) {
sum[i + 1][j + 1] = sum[i][j + 1] + sum[i + 1][j] - sum[i][j]
+ a2D[i][j] * a2D[i][j];
}
int ans = Integer.MAX_VALUE;
int x = -1, y = -1;
for (int i = 0; i <= r - h; i++)
for (int j = 0; j <= c - w; j++) {
int innerProd = res[i * c + j + b.length - 1];
if (innerProd > MOD / 2) {
innerProd -= MOD;
}
int val = sum[i + h][j + w] - sum[i + h][j] - sum[i][j + w]
+ sum[i][j] + sumBSq - 2 * innerProd;
if (val < ans) {
ans = val;
x = i;
y = j;
}
}
out.println(ans);
out.println((x + 1) + " " + (y + 1));
}
void reverse(int[] arr) {
for (int i = 0, j = arr.length - 1; i < j; i++, j--) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
Solution() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
}
public static void main(String[] args) throws IOException {
new Solution();
}
String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
return null;
}
}
return st.nextToken();
}
String nextString() {
try {
return br.readLine();
} catch (IOException e) {
eof = true;
return null;
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
}
In C :
#include <stdio.h>
#define SZ(X) ((int)(X).size())
#define ALL(X) (X).begin(), (X).end()
#define REP(I, N) for (int I = 0; I < (N); ++I)
#define REPP(I, A, B) for (int I = (A); I < (B); ++I)
#define RI(X) scanf("%d", &(X))
#define RII(X, Y) scanf("%d%d", &(X), &(Y))
#define RIII(X, Y, Z) scanf("%d%d%d", &(X), &(Y), &(Z))
#define DRI(X) int (X); scanf("%d", &X)
#define DRII(X, Y) int X, Y; scanf("%d%d", &X, &Y)
#define DRIII(X, Y, Z) int X, Y, Z; scanf("%d%d%d", &X, &Y, &Z)
#define RS(X) scanf("%s", (X))
#define CASET int ___T, case_n = 1; scanf("%d ", &___T); while (___T-- > 0)
#define MP make_pair
#define PB push_back
#define MS0(X) memset((X), 0, sizeof((X)))
#define MS1(X) memset((X), -1, sizeof((X)))
#define LEN(X) strlen(X)
#define F first
#define S second
typedef long long LL;
inline int pow(long long n,int k,int m){
unsigned i;
int a;
for(a=i=1;i<=k;i*=2,n=(n*n)%m)
if(k&i)a=(a*n)%m;
return a;
}
int rr[512];
inline int rev(int n,int k){
int i=0;
while(k--)i=(i<<1)|(n&1),n/=2;
return i;
}
const long long p=1107296257,r=10;
LL ww[513][2];
void ntt(int f,int n,int s[]){
int i,j,k=10;
long long x,w;
for(i=0;i<n;i++)
if(i<rr[i]){
int tmp=s[i];
s[i]=s[rr[i]];
s[rr[i]]=tmp;
}
for(i=2;i<=n;i<<=1){
w=ww[i][f];
for(j=0;j<n;j+=i)
for(k=0,x=1;k<i/2;k++){
int a=s[j+k],b=s[j+k+i/2];
LL tmp=b*x;
b=(a-tmp)%p;
if(b<0)b+=p;
a=(a+tmp)%p;
s[j+k]=a;
s[j+k+i/2]=b;
x=x*w%p;
}
}
x=pow(n,p-2,p);
if(f)for(j=0;j<n;j++)
s[j]=(s[j]*x)%p;
}
void mul(int n,int cc[],int a[],int b[]){
for(int i=0;i<n;i++)
cc[i]=(1ll*a[i]*b[i])%p;
}
int A[501][512],B[501][512],an[501][501],tmp[512];
int main(){
REP(i,512)rr[i]=rev(i,9);
for(int i=2;i<=512;i<<=1)
for(int f=0;f<2;f++)ww[i][f]=pow(pow(r,(p-1)/512,p),f?p-1-512/i:512/i,p);
DRII(R,C);
REP(i,R)REP(j,C){
RI(A[i][j]);
A[i][j]+=20;
}
DRII(H,W);
int base=0;
REP(i,H)REP(j,W){
RI(B[i][j]);
B[i][j]+=20;
base+=B[i][j]*B[i][j];
}
for(int i=0;i+H<=R;i++)
for(int j=0;j+W<=C;j++)an[i][j]+=base;
REP(i,R){
base=0;
for(int j=0;j<C;j++){
base+=A[i][j]*A[i][j];
if(j>=W-1){
for(int k=0;k<H&&k<=i;k++)an[i-k][j-W+1]+=base;
base-=A[i][j-W+1]*A[i][j-W+1];
}
}
}
REP(i,R){
for(int j=0;j<C-1-j;j++){
int tmp=A[i][j];
A[i][j]=A[i][C-1-j];
A[i][C-1-j]=tmp;
}
ntt(0,512,A[i]);
}
REP(i,W)ntt(0,512,B[i]);
REP(i,H){
for(int j=0;j+H<=R;j++){
mul(512,tmp,A[i+j],B[i]);
ntt(1,512,tmp);
//mul(500,B[i],A[j+i],tmp);
for(int k=0;k+W<=C;k++){
an[j][k]-=2*tmp[W-1+(C-W-k)];
}
}
}
int mi=2e9,xx,yy;
for(int i=0;i+H<=R;i++)
for(int j=0;j+W<=C;j++){
if(an[i][j]<mi){
mi=an[i][j];
xx=i+1;yy=j+1;
}
}
printf("%d\n%d %d\n",mi,xx,yy);
return 0;
}
View More Similar Problems
Binary Search Tree : Insertion
You are given a pointer to the root of a binary search tree and values to be inserted into the tree. Insert the values into their appropriate position in the binary search tree and return the root of the updated binary tree. You just have to complete the function. Input Format You are given a function, Node * insert (Node * root ,int data) { } Constraints No. of nodes in the tree <
View Solution →Tree: Huffman Decoding
Huffman coding assigns variable length codewords to fixed length input characters based on their frequencies. More frequent characters are assigned shorter codewords and less frequent characters are assigned longer codewords. All edges along the path to a character contain a code digit. If they are on the left side of the tree, they will be a 0 (zero). If on the right, they'll be a 1 (one). Only t
View Solution →Binary Search Tree : Lowest Common Ancestor
You are given pointer to the root of the binary search tree and two values v1 and v2. You need to return the lowest common ancestor (LCA) of v1 and v2 in the binary search tree. In the diagram above, the lowest common ancestor of the nodes 4 and 6 is the node 3. Node 3 is the lowest node which has nodes and as descendants. Function Description Complete the function lca in the editor b
View Solution →Swap Nodes [Algo]
A binary tree is a tree which is characterized by one of the following properties: It can be empty (null). It contains a root node only. It contains a root node with a left subtree, a right subtree, or both. These subtrees are also binary trees. In-order traversal is performed as Traverse the left subtree. Visit root. Traverse the right subtree. For this in-order traversal, start from
View Solution →Kitty's Calculations on a Tree
Kitty has a tree, T , consisting of n nodes where each node is uniquely labeled from 1 to n . Her friend Alex gave her q sets, where each set contains k distinct nodes. Kitty needs to calculate the following expression on each set: where: { u ,v } denotes an unordered pair of nodes belonging to the set. dist(u , v) denotes the number of edges on the unique (shortest) path between nodes a
View Solution →Is This a Binary Search Tree?
For the purposes of this challenge, we define a binary tree to be a binary search tree with the following ordering requirements: The data value of every node in a node's left subtree is less than the data value of that node. The data value of every node in a node's right subtree is greater than the data value of that node. Given the root node of a binary tree, can you determine if it's also a
View Solution →