【01BFS】# P4667 [BalticOI 2011] Switch the Lamp On 电路维修 (Day1)|普及+

本文涉及知识点

C++BFS算法

题目描述

Casper is designing an electronic circuit on a N × M N \times M N×M rectangular grid plate. There are N × M N \times M N×M square tiles that are aligned to the grid on the plate. Two (out of four) opposite corners of each tile are connected by a wire.

A power source is connected to the top left corner of the plate. A lamp is connected to the bottom right corner of the plate. The lamp is on only if there is a path of wires connecting power source to lamp. In order to switch the lamp on, any number of tiles can be turned by 90° (in both directions).
在这里插入图片描述

在这里插入图片描述

In the picture above the lamp is off. If any one of the tiles in the second column from the right is turned by 90° , power source and lamp get connected, and the lamp is on.

Write a program to find out the minimal number of tiles that have to be turned by 90° to switch the lamp on.

输入格式

The first line of input contains two integer numbers N N N and M M M, the dimensions of the plate. In each of the following N N N lines there are M M M symbols – either \ or / – which indicate the direction of the wire connecting the opposite vertices of the corresponding tile.

输出格式

There must be exactly one line of output. If it is possible to switch the lamp on, this line must contain only one integer number: the minimal number of tiles that have to be turned to switch on the lamp. If it is not possible, output the string: NO SOLUTION

输入输出样例 #1

输入 #1

3 5
\\/\\
\\///
/\\\\

输出 #1

1

说明/提示

对于 40 % 40\% 40% 的数据, 1 ≤ N ≤ 4 1 \le N \le 4 1N4 1 ≤ M ≤ 5 1 \le M \le 5 1M5

对于所有数据, 1 ≤ N , M ≤ 500 1 \le N,M \le 500 1N,M500

BFS 双向队列

一,本题是点图,不是单格图。故:r ∈ \in [0,N],c ∈ \in [0,M]。
二,本题能否保证每个点都只访问一次?vis记录最少改变次数,改变次数变少,才需要重新处理当前点的后续。因为是01BFS,所以可以保证所有节点只访问一次。
三,用双向队列,如果不改变入队首,改变入队尾。这样优先处理不改变,可以提速。
时间复杂度:O(NM)
任意时刻:双向队列要么全部是x,要么前边是x,后边是x+1。
x入队首,x+1入队尾,扔保持这种状态。故x处理完之前,不会处理x+1。

代码

核心代码

#include <iostream>
#include <sstream>
#include <vector>
#include<map>
#include<unordered_map>
#include<set>
#include<unordered_set>
#include<string>
#include<algorithm>
#include<functional>
#include<queue>
#include <stack>
#include<iomanip>
#include<numeric>
#include <math.h>
#include <climits>
#include<assert.h>
#include<cstring>
#include<list>#include <bitset>
using namespace std;template<class T1, class T2>
std::istream& operator >> (std::istream& in, pair<T1, T2>& pr) {in >> pr.first >> pr.second;return in;
}template<class T1, class T2, class T3 >
std::istream& operator >> (std::istream& in, tuple<T1, T2, T3>& t) {in >> get<0>(t) >> get<1>(t) >> get<2>(t) ;return in;
}template<class T1, class T2, class T3, class T4 >
std::istream& operator >> (std::istream& in, tuple<T1, T2, T3, T4>& t) {in >> get<0>(t) >> get<1>(t) >> get<2>(t) >> get<3>(t);return in;
}template<class T = int>
vector<T> Read() {int n;scanf("%d", &n);vector<T> ret(n);for(int i=0;i < n ;i++) {cin >> ret[i];}return ret;
}template<class T = int>
vector<T> Read(int n) {vector<T> ret(n);for (int i = 0; i < n; i++) {cin >> ret[i];}return ret;
}template<int N = 12 * 1'000'000>
class COutBuff
{
public:COutBuff() {m_p = puffer;}template<class T>void write(T x) {int num[28], sp = 0;if (x < 0)*m_p++ = '-', x = -x;if (!x)*m_p++ = 48;while (x)num[++sp] = x % 10, x /= 10;while (sp)*m_p++ = num[sp--] + 48;}inline void write(char ch){*m_p++ = ch;}inline void ToFile() {fwrite(puffer, 1, m_p - puffer, stdout);}
private:char  puffer[N], * m_p;
};template<int N = 12 * 1'000'000>
class CInBuff
{
public:inline CInBuff() {fread(buffer, 1, N, stdin);}inline int Read() {int x(0), f(0);while (!isdigit(*S))f |= (*S++ == '-');while (isdigit(*S))x = (x << 1) + (x << 3) + (*S++ ^ 48);return f ? -x : x;}
private:char buffer[N], * S = buffer;
};template<class TSave, class TRecord >
class CRangUpdateLineTree
{
protected:virtual void OnQuery(const TSave& save, const int& iSaveLeft, const int& iSaveRight) = 0;virtual void OnUpdate(TSave& save, const int& iSaveLeft, const int& iSaveRight, const TRecord& update) = 0;virtual void OnUpdateParent(TSave& par, const TSave& left, const TSave& r, const int& iSaveLeft, const int& iSaveRight) = 0;virtual void OnUpdateRecord(TRecord& old, const TRecord& newRecord) = 0;
};template<class TSave, class TRecord >
class CVectorRangeUpdateLineTree : public CRangUpdateLineTree<TSave, TRecord>
{
public:CVectorRangeUpdateLineTree(int iEleSize, TSave tDefault, TRecord tRecordNull) :m_iEleSize(iEleSize), m_save(iEleSize * 4, tDefault), m_record(iEleSize * 4, tRecordNull) {m_recordNull = tRecordNull;}void Update(int iLeftIndex, int iRightIndex, TRecord value){Update(1, 0, m_iEleSize - 1, iLeftIndex, iRightIndex, value);}void Query(int leftIndex, int rightIndex) {Query(1, 0, m_iEleSize - 1, leftIndex, rightIndex);}//void Init() {//	Init(1, 0, m_iEleSize - 1);//}TSave QueryAll() {return m_save[1];}void swap(CVectorRangeUpdateLineTree<TSave, TRecord>& other) {m_save.swap(other.m_save);m_record.swap(other.m_record);std::swap(m_recordNull, other.m_recordNull);assert(m_iEleSize == other.m_iEleSize);}
protected://void Init(int iNodeNO, int iSaveLeft, int iSaveRight)//{//	if (iSaveLeft == iSaveRight) {//		this->OnInit(m_save[iNodeNO], iSaveLeft);//		return;//	}//	const int mid = iSaveLeft + (iSaveRight - iSaveLeft) / 2;//	Init(iNodeNO * 2, iSaveLeft, mid);//	Init(iNodeNO * 2 + 1, mid + 1, iSaveRight);//	this->OnUpdateParent(m_save[iNodeNO], m_save[iNodeNO * 2], m_save[iNodeNO * 2 + 1], iSaveLeft, iSaveRight);//}void Query(int iNodeNO, int iSaveLeft, int iSaveRight, int iQueryLeft, int iQueryRight) {if ((iSaveLeft >= iQueryLeft) && (iSaveRight <= iQueryRight)) {this->OnQuery(m_save[iNodeNO], iSaveLeft, iSaveRight);return;}if (iSaveLeft == iSaveRight) {//没有子节点return;}Fresh(iNodeNO, iSaveLeft, iSaveRight);const int mid = iSaveLeft + (iSaveRight - iSaveLeft) / 2;if (mid >= iQueryLeft) {Query(iNodeNO * 2, iSaveLeft, mid, iQueryLeft, iQueryRight);}if (mid + 1 <= iQueryRight) {Query(iNodeNO * 2 + 1, mid + 1, iSaveRight, iQueryLeft, iQueryRight);}}void Update(int iNode, int iSaveLeft, int iSaveRight, int iOpeLeft, int iOpeRight, TRecord value){if ((iOpeLeft <= iSaveLeft) && (iOpeRight >= iSaveRight)){this->OnUpdate(m_save[iNode], iSaveLeft, iSaveRight, value);this->OnUpdateRecord(m_record[iNode], value);return;}if (iSaveLeft == iSaveRight) {return;//没有子节点}Fresh(iNode, iSaveLeft, iSaveRight);const int iMid = iSaveLeft + (iSaveRight - iSaveLeft) / 2;if (iMid >= iOpeLeft){Update(iNode * 2, iSaveLeft, iMid, iOpeLeft, iOpeRight, value);}if (iMid + 1 <= iOpeRight){Update(iNode * 2 + 1, iMid + 1, iSaveRight, iOpeLeft, iOpeRight, value);}// 如果有后代,至少两个后代this->OnUpdateParent(m_save[iNode], m_save[iNode * 2], m_save[iNode * 2 + 1], iSaveLeft, iSaveRight);}void Fresh(int iNode, int iDataLeft, int iDataRight){if (m_recordNull == m_record[iNode]){return;}const int iMid = iDataLeft + (iDataRight - iDataLeft) / 2;Update(iNode * 2, iDataLeft, iMid, iDataLeft, iMid, m_record[iNode]);Update(iNode * 2 + 1, iMid + 1, iDataRight, iMid + 1, iDataRight, m_record[iNode]);m_record[iNode] = m_recordNull;}vector<TSave> m_save;vector<TRecord> m_record;TRecord m_recordNull;const int m_iEleSize;
};class C01BFSDis
{
public:C01BFSDis(vector<vector<int>>& vNeiB0, vector<vector<int>>& vNeiB1, int s){m_vDis.assign(vNeiB0.size(), -1);std::deque<std::pair<int, int>> que;que.emplace_back(s, 0);while (que.size()){auto it = que.front();const int cur = it.first;const int dis = it.second;que.pop_front();if (-1 != m_vDis[cur]){continue;}m_vDis[cur] = it.second;for (const auto next : vNeiB0[cur]){if (-1 != m_vDis[next]){continue;}que.emplace_front(next, dis);}for (const auto next : vNeiB1[cur]){if (-1 != m_vDis[next]){continue;}que.emplace_back(next, dis + 1);}}}
public:vector<int> m_vDis;
};class Solution {
public:int Ans(vector<string>& mat) {const int R = mat.size();const int C = mat[0].size();auto Mask = [&](int r, int c) {return (C + 1) * r + c;};const int iMC = (R + 1) * (C + 1);vector<vector<int>> neiBo0(iMC), neiBo1(iMC);for (int r = 0; r < R; r++) {for (int c = 0; c < C; c++) {const int mask1 = Mask(r, c);const int mask2 = Mask(r + 1, c + 1);const int mask3 = Mask(r + 1, c);const int mask4 = Mask(r, c + 1);if ('\\' == mat[r][c]) {neiBo0[mask1].emplace_back(mask2);neiBo0[mask2].emplace_back(mask1);neiBo1[mask3].emplace_back(mask4);neiBo1[mask4].emplace_back(mask3);}else {neiBo0[mask3].emplace_back(mask4);neiBo0[mask4].emplace_back(mask3);neiBo1[mask1].emplace_back(mask2);neiBo1[mask2].emplace_back(mask1);}}}C01BFSDis bfs(neiBo0, neiBo1, 0);return bfs.m_vDis.back();}};int main() {
#ifdef _DEBUGfreopen("a.in", "r", stdin);
#endif // DEBUG	int R, C;cin >> R >> C;vector<string> mat(R);for (int r = 0; r < R; r++) {cin >> mat[r];}auto res = Solution().Ans(mat);if (res < 0) {cout << "NO SOLUTION";}else {cout << res;}	
#ifdef _DEBUG		/*printf("T=%d,", T);*/Out(mat, "mat=");
#endif // DEBUG	return 0;
}

单元测试

vector<string> mat;TEST_METHOD(TestMethod11){mat = { {"\\/"} };auto res = Solution().Ans(mat);AssertEx(-1, res);}TEST_METHOD(TestMethod12){mat = { {"\\/\\"} };auto res = Solution().Ans(mat);AssertEx(0, res);}TEST_METHOD(TestMethod13){mat = { {"///"} };auto res = Solution().Ans(mat);AssertEx(2, res);}TEST_METHOD(TestMethod14){mat = { "\\\\/\\\\","\\\\///","/\\\\\\\\" };auto res = Solution().Ans(mat);AssertEx(1, res);}

扩展阅读

我想对大家说的话
工作中遇到的问题,可以按类别查阅鄙人的算法文章,请点击《算法与数据汇总》。
学习算法:按章节学习《喜缺全书算法册》,大量的题目和测试用例,打包下载。重视操作
有效学习:明确的目标 及时的反馈 拉伸区(难度合适) 专注
闻缺陷则喜(喜缺)是一个美好的愿望,早发现问题,早修改问题,给老板节约钱。
子墨子言之:事无终始,无务多业。也就是我们常说的专业的人做专业的事。
如果程序是一条龙,那算法就是他的是睛
失败+反思=成功 成功+反思=成功

视频课程

先学简单的课程,请移步CSDN学院,听白银讲师(也就是鄙人)的讲解。
https://edu.csdn.net/course/detail/38771
如何你想快速形成战斗了,为老板分忧,请学习C#入职培训、C++入职培训等课程
https://edu.csdn.net/lecturer/6176

测试环境

操作系统:win7 开发环境: VS2019 C++17
或者 操作系统:win10 开发环境: VS2022 C++17
如无特殊说明,本算法用**C++**实现。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/75263.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

参考平面跨分割情况下的信号回流

前言&#xff1a;弄清楚信号的回流路径&#xff0c;是学习EMC和高速的第一步&#xff01; 如果我们不管信号的回流路径&#xff0c;会造成什么后果&#xff1f;1、信号完整性问题&#xff0c;信号的回流路径不连续会导致信号反射、衰减和失真。2、信号衰减和噪声干扰&#xff…

almalinux 8 9 升级到指定版本

almalinux 8 update 指定版本 almalinux历史版 所有版本almalinux最新版 所有版本vault历史版 almalinux最新版 (https://repo.almalinux.org )地址后面增加不同名称 echo "delete repos" rm -rf /etc/yum.repos.d/*echo "new almalinux repo" cat <&…

阿里云CDN应对DDoS攻击策略

阿里云CDN遭遇DDoS攻击时&#xff0c;可通过以下综合措施进行应对&#xff0c;保障服务的稳定性和可用性&#xff1a; 1. 启用阿里云DDoS防护服务 阿里云提供专业的DDoS防护服务&#xff0c;通过流量清洗中心过滤恶意流量&#xff0c;确保合法请求正常传输。该服务支持按需选…

CentOS Stream release 9安装 MySQL(一)

在 CentOS Stream 上安装 MySQL 的方法与传统的 CentOS 类似&#xff0c;但由于 CentOS Stream 的软件包更新策略不同&#xff0c;可能会遇到一些依赖问题。以下是详细安装步骤&#xff1a; 1. 添加 MySQL 官方 Yum 仓库 sudo rpm -Uvh https://dev.mysql.com/get/mysql80-co…

数据结构 | 证明链表环结构是否存在

❤个人主页&#xff1a; 链表环结构 0.前言1.环形链表&#xff08;基础&#xff09;2.环形链表Ⅱ&#xff08;中等&#xff09;3.证明相遇条件及结论3.1 问题1特殊情况证明3.2 问题1普适性证明 0.前言 在这篇博客中&#xff0c;我们将深入探讨链表环结构的检测方法&#xff1a;…

数字世界的免疫系统:恶意流量检测如何守护网络安全

在2023年全球网络安全威胁报告中,某跨国电商平台每秒拦截的恶意请求峰值达到217万次,这个数字背后是无数黑客精心设计的自动化攻击脚本。恶意流量如同数字世界的埃博拉病毒,正在以指数级速度进化,传统安全防线频频失守。这场没有硝烟的战争中,恶意流量检测技术已成为守护网…

【JavaScript】十八、页面加载事件和页面滚动事件

文章目录 1、页面加载事件1.1 load1.2 DOMContentLoaded 2、页面滚动事件2.1 语法2.2 获取滚动位置 3、案例&#xff1a;页面滚动显示隐藏侧边栏 1、页面加载事件 script标签在html中的位置一般在</body>标签上方&#xff0c;这是因为代码从上往下执行&#xff0c;在htm…

Linux : 内核中的信号捕捉

目录 一 前言 二 信号捕捉的方法 1.sigaction()​编辑 2. sigaction() 使用 三 可重入函数 四 volatile 关键字 一 前言 如果信号的处理动作是用户自定义函数,在信号递达时就调用这个函数,这称为捕捉信号。在Linux: 进程信号初识-CSDN博客 这一篇中已经学习到了一种信号…

分布式id生成算法(雪花算法 VS 步长id生成)

分布式ID生成方案详解:雪花算法 vs 步长ID 一、核心需求 全局唯一性:集群中绝不重复有序性:有利于数据库索引性能高可用:每秒至少生成数万ID低延迟:生成耗时<1ms二、雪花算法(Snowflake) 1. 数据结构(64位) 0 | 0000000000 0000000000 0000000000 0000000000 0 |…

函数式编程在 Java:Function、BiFunction、UnaryOperator 你真的会用?

大家好&#xff0c;我是你们的Java技术博主&#xff01;今天我们要深入探讨Java函数式编程中的几个核心接口&#xff1a;Function、BiFunction和UnaryOperator。很多同学虽然知道它们的存在&#xff0c;但真正用起来却总是不得要领。这篇文章将带你彻底掌握它们&#xff01;&am…

x265 编码器中运动搜索 ME 方法对比实验

介绍 x265 的运动搜索方法一共有 6 种方法,分别是 DIA、HEX、UMH、STAR、SEA、FULL。typedef enum {X265_DIA_SEARCH,X265_HEX_SEARCH,X265_UMH_SEARCH,X265_STAR_SEARCH,X265_SEA,X265_FULL_SEARCH } X265_ME_METHODS;GitHub

2025.4.8 dmy NOI模拟赛总结(转化贡献方式 dp, 交互(分段函数找断点),SAM上计数)

文章目录 时间安排题解T1.搬箱子(dp&#xff0c;转化贡献方式)T2.很多线。(分段函数找断点)T3.很多串。(SAM&#xff0c; 计数) 时间安排 先写了 T 3 T3 T3 60 p t s 60pts 60pts&#xff0c;然后剩下 2.5 h 2.5h 2.5h 没有战胜 T 1 T1 T1 40 p t s 40pts 40pts。 总得分…

ZYNQ笔记(四):AXI GPIO

版本&#xff1a;Vivado2020.2&#xff08;Vitis&#xff09; 任务&#xff1a;使用 AXI GPIO IP 核实现按键 KEY 控制 LED 亮灭&#xff08;两个都在PL端&#xff09; 一、介绍 AXI GPIO (Advanced eXtensible Interface General Purpose Input/Output) 是 Xilinx 提供的一个可…

CSP认证准备第二天-第36/37次CCF认证

第37次CCF认证-第三题 主要是间接赋值比较难。 自己编写的代码如下&#xff0c;但是有问题&#xff0c;没有解决间接赋值的问题&#xff0c;可以参考一下deepseek的回答。 #include <iostream> #include <bits/stdc.h> using namespace std; long long n,x; char …

Kotlin与HttpClient编写视频爬虫

想用Apache HttpClient库和Kotlin语言写一个视频爬虫。首先&#xff0c;我需要确定用户的具体需求。视频爬虫通常涉及发送HTTP请求&#xff0c;解析网页内容&#xff0c;提取视频链接&#xff0c;然后下载视频。可能需要处理不同的网站结构&#xff0c;甚至可能需要处理动态加载…

FFMEPG常见命令查询

基本参数 表格1&#xff1a;主要参数 参数说明-i设定输入流-f设定输出格式(format) 高于后缀名-ss开始时间-t时间长度codec编解码 表格2&#xff1a;音频参数 参数说明-aframes设置要输出的音频帧数-f音频帧深度-b:a音频码率-ar设定采样率-ac设定声音的Channel数-acodec设定…

Java-对比两组对象找出发生变化的字段工具-支持枚举映射-支持时间-支持显示对应字段中文描述-嵌套list等场景

实体字段比较器&#xff08;对比两组对象找出发生变化的字段工具类开发&#xff09; 支持枚举映射 支持时间 支持显示对应字段中文描述 支持嵌套list等场景 下载地址&#xff1a; Java-对比两组对象找出发生变化的字段工具-支持枚举映射-支持时间-支持显示对应字段中文描述-嵌…

15. git push

基本概述 git push 的作用是&#xff1a;把本地分支的提交推送到远程仓库。推送分支需要满足快进规则&#xff08;Fast-Forward&#xff09;&#xff0c;即远程分支的最新提交必须是本地分支的直接祖先&#xff0c;这个是通过哈希值值进行判断的。 基本用法 1.完整格式 git…

训练数据清洗(文本/音频/视频)

多数据格式的清洗方法 以下是针对多数据格式清洗方法的系统性总结&#xff0c;结合Python代码示例&#xff1a; 一、数据清洗方法总览&#xff08;表格对比&#xff09; 数据类型核心挑战关键步骤常用Python工具文本非结构化噪声去噪→分词→标准化→向量化NLTK, SpaCy, Jie…

Python标准库json完全指南:高效处理JSON数据

一、json库概述 JSON(JavaScript Object Notation)是一种轻量级的数据交换格式&#xff0c;Python的json模块提供了JSON数据的编码和解码功能。该模块可以将Python对象转换为JSON字符串&#xff08;序列化&#xff09;&#xff0c;也可以将JSON字符串转换为Python对象&#xf…