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 :



title-img


                            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

Fibonacci Numbers Tree

Shashank loves trees and math. He has a rooted tree, T , consisting of N nodes uniquely labeled with integers in the inclusive range [1 , N ]. The node labeled as 1 is the root node of tree , and each node in is associated with some positive integer value (all values are initially ). Let's define Fk as the Kth Fibonacci number. Shashank wants to perform 22 types of operations over his tree, T

View Solution →

Pair Sums

Given an array, we define its value to be the value obtained by following these instructions: Write down all pairs of numbers from this array. Compute the product of each pair. Find the sum of all the products. For example, for a given array, for a given array [7,2 ,-1 ,2 ] Note that ( 7 , 2 ) is listed twice, one for each occurrence of 2. Given an array of integers, find the largest v

View Solution →

Lazy White Falcon

White Falcon just solved the data structure problem below using heavy-light decomposition. Can you help her find a new solution that doesn't require implementing any fancy techniques? There are 2 types of query operations that can be performed on a tree: 1 u x: Assign x as the value of node u. 2 u v: Print the sum of the node values in the unique path from node u to node v. Given a tree wi

View Solution →

Ticket to Ride

Simon received the board game Ticket to Ride as a birthday present. After playing it with his friends, he decides to come up with a strategy for the game. There are n cities on the map and n - 1 road plans. Each road plan consists of the following: Two cities which can be directly connected by a road. The length of the proposed road. The entire road plan is designed in such a way that if o

View Solution →

Heavy Light White Falcon

Our lazy white falcon finally decided to learn heavy-light decomposition. Her teacher gave an assignment for her to practice this new technique. Please help her by solving this problem. You are given a tree with N nodes and each node's value is initially 0. The problem asks you to operate the following two types of queries: "1 u x" assign x to the value of the node . "2 u v" print the maxim

View Solution →

Number Game on a Tree

Andy and Lily love playing games with numbers and trees. Today they have a tree consisting of n nodes and n -1 edges. Each edge i has an integer weight, wi. Before the game starts, Andy chooses an unordered pair of distinct nodes, ( u , v ), and uses all the edge weights present on the unique path from node u to node v to construct a list of numbers. For example, in the diagram below, Andy

View Solution →