Practical Skill Test 前缀和

Practical Skill Test

时间限制: 1 Sec 内存限制: 128 MB

题目描述
We have a grid with H rows and W columns. The square at the i-th row and the j-th column will be called Square (i,j).
The integers from 1 through H×W are written throughout the grid, and the integer written in Square (i,j) is Ai,j.
You, a magical girl, can teleport a piece placed on Square (i,j) to Square (x,y) by consuming |x−i|+|y−j| magic points.
You now have to take Q practical tests of your ability as a magical girl.
The i-th test will be conducted as follows:
Initially, a piece is placed on the square where the integer Li is written.
Let x be the integer written in the square occupied by the piece. Repeatedly move the piece to the square where the integer x+D is written, as long as x is not Ri. The test ends when x=Ri.
Here, it is guaranteed that Ri−Li is a multiple of D.
For each test, find the sum of magic points consumed during that test.

Constraints
1≤H,W≤300
1≤D≤H×W
1≤Ai,j≤H×W
Ai,j≠Ax,y((i,j)≠(x,y))
1≤Q≤105
1≤Li≤Ri≤H×W
(Ri−Li) is a multiple of D.
输入
Input is given from Standard Input in the following format:
H W D
A1,1 A1,2 … A1,W
:
AH,1 AH,2 … AH,W
Q
L1 R1
:
LQ RQ
输出
For each test, print the sum of magic points consumed during that test.
Output should be in the order the tests are conducted.
样例输入 Copy
3 3 2
1 4 3
2 5 7
8 9 6
1
4 8
样例输出 Copy
5
提示
4 is written in Square (1,2).
6 is written in Square (3,3).
8 is written in Square (3,1).
Thus, the sum of magic points consumed during the first test is (|3−1|+|3−2|)+(|3−3|+|1−3|)=5.

题意就是给你个方格,里面都填的数,让后给你个 l 和 r ,l 对应方格中的数的位置,只要 l != r 就给 l 加上 d ,一直到 l = r 为止,计算要走的距离 ,每一个距离就是 l 和 l + d 在方格中对应数点的曼哈顿距离。
题目中的数据一开始没看让后T掉了,一开始我是直接模拟的,while( l ! = r ) 一直循环下去,可以发现这样的时间复杂度d=1的时候从1枚举到n*m再加上询问比较多,肯定是会T掉的,所以可以考虑预处理每一个点的距离的前缀和,询问直接 O(1) 查询即可。
dis是从起点到这个点的距离。

#include<cstdio>
#include<iostream>
#include<string>
#include<cstring>
#include<map>
#include<cctype>
#include<vector>
#include<set>
#include<queue>
#include<algorithm>
#include<sstream>
#define X first
#define Y second
using namespace std;

typedef long long LL;
typedef pair<int,int> PII;

const int N=510,mod=1e9+7;

LL gcd(LL a,LL b) {return b? gcd(b,a%b):a;};

int n,m,d,q;
int dis[2*N*N];
map<int,PII>p;

int main()
{
//	ios::sync_with_stdio(false);
//	cin.tie(0);

	scanf("%d%d%d",&n,&m,&d);
	
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)
		{
			int x;
			scanf("%d",&x);
			p[x]={i,j};
		}
	}
	
	int row,col,px,py;
	
	for(int i=1;i<=n*m;i++)
	{
		if(i+d>n*m) break;

		px=p[i].X,py=p[i].Y;
		row=p[i+d].X,col=p[i+d].Y;

		dis[i+d]=dis[i]+abs(px-row)+abs(py-col);
	}

	scanf("%d",&q);
	
	while(q--)
	{
		int l,r;
		scanf("%d%d",&l,&r);
		
		printf("%d\n",dis[r]-dis[l]);
	}



	return 0;
}










发布了43 篇原创文章 · 获赞 1 · 访问量 1577

猜你喜欢

转载自blog.csdn.net/DaNIelLAk/article/details/105025821