CF1749E Cactus Wall

知识点:图论,最短路

难度:6

这个题是2400的题,还是比较有难度的,关键要想到,这个题和紫书上面第6章的例题比较像,那上面的分类是对偶图,没学过所以不知道是啥,所以这里比较像思维里面的问题转换啥的,题目问的是能不能从上边任意一点进入,从下边任意一点出去,不能的话最少需要加多少个障碍,障碍不能四联通的方式摆放,问题转化,转化为,有没有一种方式,使得从左边到右边摆放障碍(以斜四联通的方式),求出最少增加多少个障碍,再转化成最短路问题,左边一列都是起点,然后求到右边的最短路,按照斜四联通的方式扩展,并且扩展的点四联通的位置没有障碍,并且扩展的点是障碍,那么距离是0,如果是空地,那么距离是1,表示要增加一个障碍,这样这个问题就转化为01最短路问题,最后求出来的最短路的值就是要加多少障碍,题目说的是任意输出一种障碍的情况,那么求最短路的时候任意记录一种情况就行了,这样这个题就完成了

一句话,这个题的难点在于把问题转化为求左边到右边的斜连通01最短路问题,

#include <bits/stdc++.h>

using namespace std;

const int N = 2e5 + 5, Inf = 1e9;

struct node {
	int x, y, step;
	node() {}
	node(int a, int b, int c): x(a), y(b), step(c) {}
};

int n, m;
int dx[8] = {-1, 0, 1, 0, -1, -1, 1, 1};
int dy[8] = {0, 1, 0, -1, -1, 1, 1, -1};
vector<int> h[N], dist[N], pre[N];
string s[N];

bool check(int x, int y) {
	if (x < 0 || x >= n || y < 0 || y >= m) return false;
	for (int i = 0; i < 4; i++) {
		int x1 = x + dx[i];
		int y1 = y + dy[i];
		if (x1 < 0 || x1 >= n || y1 < 0 || y1 >= m) continue;
		if (s[x1][y1] == '#') return false;
	}
	return true;
}

void print(int x, int y) {
	while (true) {
		s[x][y] = '#';
		if (!y) break;
		int tmp = pre[x][y];
		x = tmp / m;
		y = tmp % m;
	}
	cout << "YES\n";
	for (int i = 0; i < n; i++) {
		cout << s[i] << '\n';
	}
	return;
}

void bfs() {
	for (int i = 0; i < n; i++) {
		h[i].clear();
		dist[i].clear();
		pre[i].clear();
		for (int j = 0; j < m; j++) {
			h[i].push_back(0);
			dist[i].push_back(Inf);
			pre[i].push_back(Inf);
		}
	}
	deque<node> q;
	for (int i = 0; i < n; i++) {
		if (!check(i, 0)) continue;
		if (s[i][0] == '#') q.push_front(node(i, 0, 0));
		else q.push_back(node(i, 0, 1));
	}
	while (!q.empty()) {
		node now = q.front(); q.pop_front();
		if (now.y == m - 1) { print(now.x, m - 1); return; }
		if (h[now.x][now.y]) continue;
		h[now.x][now.y] = 1;
		dist[now.x][now.y] = now.step;
		for (int i = 4; i < 8; i++) {
			int x1 = now.x + dx[i];
			int y1 = now.y + dy[i];
			if (!check(x1, y1)) continue;
			if (s[x1][y1] == '#') {
				q.push_front(node(x1, y1, now.step));
				if (now.step < dist[x1][y1]) {
					dist[x1][y1] = now.step;
					pre[x1][y1] = now.x * m + now.y;
				}
			} else {
				q.push_back(node(x1, y1, now.step + 1));
				if (now.step + 1 < dist[x1][y1]) {
					dist[x1][y1] = now.step + 1;
					pre[x1][y1] = now.x * m + now.y;
				}
			}
		}
	}
	cout << "NO\n";
}

int main() {
	int T;
	cin >> T;
	while (T--) {
		cin >> n >> m;
		for (int i = 0; i < n; i++) {
			cin >> s[i];
		}
		bfs();
	}
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值