unittest
{
	assert( [ "3 3 2", "1 4 3", "2 5 7", "8 9 6", "1", "4 8" ].parse.expand.solve == "5" );
	assert( [ "4 2 3", "3 7", "1 4", "5 2", "6 8", "2", "2 2", "2 2" ].parse.expand.solve == "0\n0" );
	assert( [ "5 5 4", "13 25 7 15 17", "16 22 20 2 9", "14 11 12 1 19", "10 6 23 8 18", "3 21 5 24 4", "3", "13 13", "2 10", "13 13" ].parse.expand.solve == "0\n5\n0" );
}



import std.algorithm;
import std.conv;
import std.math;
import std.range;
import std.stdio;
import std.typecons;

void main()
{
	stdin.byLineCopy.parse.expand.solve.writeln;
}

auto parse( Range )( Range input )
if( isInputRange!Range && is( ElementType!Range == string ) )
{
	auto hwd = input.front.split.to!( long[] );
	auto ass = new long[][]( hwd[ 0 ], hwd[ 1 ] );
	foreach( ref as; ass )
	{
		input.popFront;
		as = input.front.split.to!( long[] );
	}
	input.popFront;
	auto q = input.front.to!( long );
	auto lrs = new long[ 2 ][ q ];
	foreach( ref lr; lrs )
	{
		input.popFront;
		lr = input.front.split.to!( long[] );
	}
	return tuple( hwd[ 2 ], ass, lrs );
}

auto solve( long d, long[][] ass, long[ 2 ][] lrs )
{
	// マス目を番号基準の座標配列に変換
	auto ids = new Tuple!( long, long )[ 1 + ass.length * ass[ 0 ].length ];
	foreach( y, as; ass )
	{
		foreach( x, a; as )
		{
			ids[ a ] = tuple( y, x );
		}
	}
	
	// Lに対するRの最大値を判定
	long[ long ] rms;
	foreach( lr; lrs )
	{
		if( lr[ 0 ] !in rms ) rms[ lr[ 0 ] ] = lr[ 1 ];
		else                  rms[ lr[ 0 ] ] = max( rms[ lr[ 0 ] ], lr[ 1 ] );
	}
	
	// LからRの最大値まで移動したときの消費魔力を計算
	long[ long ][ long ] cs;
	foreach( l, rm; rms )
	{
		cs[ l ][ l ] = 0L;
		for( auto r = l; r < rm; r += d )
		{
			auto rd = r + d;
			cs[ l ][ rd ] = cs[ l ][ r ] + abs( ids[ rd ][ 0 ] - ids[ r ][ 0 ] ) + abs( ids[ rd ][ 1 ] - ids[ r ][ 1 ] );
		}
	}
	
	// 試験ごとの消費魔力を取得
	return lrs.map!( ( lr ) => cs[ lr[ 0 ] ][ lr[ 1 ] ].to!string ).join( "\n" );
}
