题解 | Distance-2019牛客暑期多校训练营第八场D题

该博客提供了2019年牛客暑期多校训练营第八场D题的详细题解,包括题目描述、输入输出说明及示例。博主分享了题解思路,并给出了代码实现。此外,鼓励读者访问牛客竞赛区获取更多题目讨论和资源。
摘要由CSDN通过智能技术生成

题目来源于牛客竞赛:https://ac.nowcoder.com/acm/contest/discuss
题目描述:
在这里插入图片描述
输入描述:
在这里插入图片描述
输出描述:
在这里插入图片描述
示例1:
在这里插入图片描述
题解:
在这里插入图片描述
代码:

#include <cmath>
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
#define N 100000 + 5
#define INF 0x3f3f3f3f

const int Fx[6][3] = {{1, 0, 0}, {0, 1, 0}, {-1, 0, 0}, {0, -1, 0}, {0, 0, 1}, {0, 0, -1}};
int n, m, h, q, k, Dis[N];

struct Point
{
	int x, y, z;
	Point (int x, int y, int z) : x(x), y(y), z(z) {}
};

vector<Point> Cache, Bank, Q;

inline int Encode(int x, int y, int z)
{
	return (x - 1) * m * h + (y - 1) * h + z;
}

void BFS()
{
	for (int i = 1; i <= n * m * h; i ++)
		Dis[i] = INF;
	for (const Point &p : Bank)
		Dis[Encode(p.x, p.y, p.z)] = 0;
	Q = Bank;
	for (size_t t = 0; t < Q.size(); t ++)
	{
		int x = Q[t].x, y = Q[t].y, z = Q[t].z, c = Encode(x, y, z);
		for (int k = 0; k < 6; k ++)
		{
			int tx = x + Fx[k][0], ty = y + Fx[k][1], tz = z + Fx[k][2];
			if (tx && ty && tz && tx <= n && ty <= m && tz <= h && Dis[Encode(tx, ty, tz)] == INF)
			{
				Dis[Encode(tx, ty, tz)] = Dis[c] + 1;
				Q.emplace_back(tx, ty, tz);
			}
		}
	}
}

int main()
{
	scanf("%d%d%d%d", &n, &m, &h, &q);
	for (int i = 1; i <= n * m * h; i ++)
		Dis[i] = INF;
	k = 3 * int(sqrt(n * m * h));
	for (int i = 1, op, x, y, z; i <= q; i ++)
	{
		scanf("%d%d%d%d", &op, &x, &y, &z);
		if (op == 1)
		{
			Cache.emplace_back(x, y, z);
			if (Cache.size() == k)
			{
				Bank.insert(Bank.end(), Cache.begin(), Cache.end());
				Cache.clear();
				BFS();
			}
		}
		else
		{
			int ans = Dis[Encode(x, y, z)];
			for (const Point &p : Cache)
				ans = min(ans, abs(p.x - x) + abs(p.y - y) + abs(p.z - z));
			printf("%d\n", ans);
		}
	}
	return 0;
}

更多问题,更详细题解可关注牛客竞赛区,一个刷题、比赛、分享的社区。
传送门:https://ac.nowcoder.com/acm/contest/discuss

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值