【回溯 剪支 状态压缩】# P10419 [蓝桥杯 2023 国 A] 01 游戏|普及+

发布于:2025-05-19 ⋅ 阅读:(21) ⋅ 点赞:(0)

本文涉及知识点

C++回溯
位运算、状态压缩、枚举子集汇总

P10419 [蓝桥杯 2023 国 A] 01 游戏

题目描述

小蓝最近玩上了 01 01 01 游戏,这是一款带有二进制思想的棋子游戏,具体来说游戏在一个大小为 N × N N\times N N×N 的棋盘上进行,棋盘上每个位置都需要放置一位数字 0 0 0 或者数字 1 1 1,初始情况下,棋盘上有一部分位置已经被放置好了固定的数字,玩家不可以再进行更改。玩家需要在其他所有的空白位置放置数字,并使得最终结果满足以下条件:

  1. 所有的空白位置都需要放置一个数字 0 / 1 0/1 0/1
  2. 在水平或者垂直方向上,相同的数字不可以连续出现大于两次;
  3. 每一行和每一列上,数字 0 0 0 和数字 1 1 1 的数量必须是相等的 (例如 N = 4 N=4 N=4,则表示每一行/列中都需要有 2 2 2 0 0 0 2 2 2 1 1 1);
  4. 每一行都是唯一的,因此每一行都不会和另一行完全相同;同理每一列也都是唯一的,每一列都不会和另一列完全相同。

现在请你和小蓝一起解决 01 01 01 游戏吧!题目保证所有的测试数据都拥有一个唯一的答案。

输入格式

输入的第一行包含一个整数 N N N 表示棋盘大小。

接下来 N N N 行每行包含 N N N 个字符,字符只可能是 01_ 中的其中一个 (ASCII 码分别为 48 48 48 49 49 49 95 95 95),0 表示这个位置数字固定为 0 0 01 表示这个位置数字固定为 1 1 1_ 表示这是一个空白位置,由玩家填充。

输出格式

输出 N N N 行每行包含 N N N 个字符表示题目的解,其中的字符只能是 0 或者 1

输入输出样例 #1

输入 #1

6
_0____
____01
__1__1
__1_0_
______
__1___

输出 #1

100110
010101
001011
101100
110010
011001

说明/提示

【评测用例规模与约定】

对于 60 % 60\% 60% 的评测用例, 2 ≤ N ≤ 6 2\le N\le 6 2N6;
对于所有评测用例, 2 ≤ N ≤ 10 2\le N\le 10 2N10 N N N 为偶数。

感谢 @rui_er 提供测试数据。

回溯 剪支 状态压缩

直接回溯,时间复杂度:O(2^nn),超时。
回溯函数参数:r, c当前行列,val当前值。
局部变量:mat记录输入,cntr[r],cntc[c]记录当前行列1的个数。rows[r],cols[c]记录已选择各行列的状态。hasrow[mask] hascol[mask]记录各状态各行是否已经选择。
r >= N,返回true。
如果r >=2 ,如果前两行和当前行相等,返回false。
如果c >=2 ,判断前两列和当前列相等,返回false。
最后一行,如果hascol[当前列状态],返回false。
最后一列,如果hasrow[当前行状态],返回false。
如果行列1或0的个数大于N/2, 返回false。
更新cntr, cntc、rows、cols、hasrow、hascol。
如果mat[r][c] 等于1或0,只枚举1或0。否则枚举0和1。
恢复cntr, cntc、rows、cols、hasrow、hascol。

代码

核心代码

#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<array>

#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 T1, class T2, class T3, class T4, class T5, class T6, class T7 >
std::istream& operator >> (std::istream& in, tuple<T1, T2, T3, T4,T5,T6,T7>& t) {
	in >> get<0>(t) >> get<1>(t) >> get<2>(t) >> get<3>(t) >> get<4>(t) >> get<5>(t) >> get<6>(t);
	return in;
}

template<class T = int>
vector<T> Read() {
	int n;
	cin >> n;
	vector<T> ret(n);
	for (int i = 0; i < n; i++) {
		cin >> ret[i];
	}
	return ret;
}
template<class T = int>
vector<T> ReadNotNum() {
	vector<T> ret;
	T tmp;
	while (cin >> tmp) {
		ret.emplace_back(tmp);
		if ('\n' == cin.get()) { break; }
	}
	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 = 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;
		AuotToFile();
	}
	void writestr(const char* sz) {
		strcpy(m_p, sz);
		m_p += strlen(sz);
		AuotToFile();
	}
	inline void write(char ch)
	{
		*m_p++ = ch;
		AuotToFile();
	}
	inline void ToFile() {
		fwrite(puffer, 1, m_p - puffer, stdout);
		m_p = puffer;
	}
	~COutBuff() {
		ToFile();
	}
private:
	inline void AuotToFile() {
		if (m_p - puffer > N - 100) {
			ToFile();
		}
	}
	char  puffer[N], * m_p;
};

template<int N = 1'000'000>
class CInBuff
{
public:
	inline CInBuff() {}
	inline CInBuff<N>& operator>>(char& ch) {
		FileToBuf();
		while (('\r' == *S) || ('\n' == *S) || (' ' == *S)) { S++; }//忽略空格和回车
		ch = *S++;
		return *this;
	}
	inline CInBuff<N>& operator>>(int& val) {
		FileToBuf();
		int x(0), f(0);
		while (!isdigit(*S))
			f |= (*S++ == '-');
		while (isdigit(*S))
			x = (x << 1) + (x << 3) + (*S++ ^ 48);
		val = f ? -x : x; S++;//忽略空格换行		
		return *this;
	}
	inline CInBuff& operator>>(long long& val) {
		FileToBuf();
		long long x(0); int f(0);
		while (!isdigit(*S))
			f |= (*S++ == '-');
		while (isdigit(*S))
			x = (x << 1) + (x << 3) + (*S++ ^ 48);
		val = f ? -x : x; S++;//忽略空格换行
		return *this;
	}
	template<class T1, class T2>
	inline CInBuff& operator>>(pair<T1, T2>& val) {
		*this >> val.first >> val.second;
		return *this;
	}
	template<class T1, class T2, class T3>
	inline CInBuff& operator>>(tuple<T1, T2, T3>& val) {
		*this >> get<0>(val) >> get<1>(val) >> get<2>(val);
		return *this;
	}
	template<class T1, class T2, class T3, class T4>
	inline CInBuff& operator>>(tuple<T1, T2, T3, T4>& val) {
		*this >> get<0>(val) >> get<1>(val) >> get<2>(val) >> get<3>(val);
		return *this;
	}
	template<class T = int>
	inline CInBuff& operator>>(vector<T>& val) {
		int n;
		*this >> n;
		val.resize(n);
		for (int i = 0; i < n; i++) {
			*this >> val[i];
		}
		return *this;
	}
	template<class T = int>
	vector<T> Read(int n) {
		vector<T> ret(n);
		for (int i = 0; i < n; i++) {
			*this >> ret[i];
		}
		return ret;
	}
	template<class T = int>
	vector<T> Read() {
		vector<T> ret;
		*this >> ret;
		return ret;
	}
private:
	inline void FileToBuf() {
		const int canRead = m_iWritePos - (S - buffer);
		if (canRead >= 100) { return; }
		if (m_bFinish) { return; }
		for (int i = 0; i < canRead; i++)
		{
			buffer[i] = S[i];//memcpy出错			
		}
		m_iWritePos = canRead;
		buffer[m_iWritePos] = 0;
		S = buffer;
		int readCnt = fread(buffer + m_iWritePos, 1, N - m_iWritePos, stdin);
		if (readCnt <= 0) { m_bFinish = true; return; }
		m_iWritePos += readCnt;
		buffer[m_iWritePos] = 0;
		S = buffer;
	}
	int m_iWritePos = 0; bool m_bFinish = false;
	char buffer[N + 10], * S = buffer;
};

class Solution {
public:
	vector<string> Ans(const int N, vector<string>& grid) {
		this->N = N;
		this->grid = grid;
		row1cnts.resize(N); col1cnts.resize(N); rows.resize(N), cols.resize(N);
		hasrow.resize(1 << N), hascol.resize(1 << N);
		BackTrack(0, 0);
		vector<string> ans;
		for (int i = 0; i < N; i++) {
			string s;
			for (int j = N - 1; j >= 0; j--) {
				s += (rows[i] & (1 << j)) ? "1" : "0";
			}
			ans.emplace_back(s);
		}
		return ans;
	}
	bool BackTrack(int r, int c) {
		if (r >= N) { return true; }
		if ('_' == grid[r][c]) {
			if (BackTrack(r, c, 0))return true;
			if (BackTrack(r, c, 1))return true;
		}
		else {
			if (BackTrack(r, c, grid[r][c] - '0'))return true;
		}
		return false;
	};
	bool BackTrack(int r, int c, int val) {
		if (r >= N) { return true; }
		//非法判断
		const int row1 = row1cnts[r] + (1 == val);
		if (row1 > N / 2) { return false; }
		if (c + 1 - row1 > N / 2) { return false; }
		const int col1 = col1cnts[c] + (1 == val);
		if (col1 > N / 2) { return false; }
		if (r + 1 - col1 > N / 2) { return false; }
		if (r >= 2) {
			if ((cols[c] & 3) == (val * 3)) {
				return false;
			}
		}
		if (c >= 2) {
			if ((rows[r] & 3) == (val * 3)) {
				return false;
			}
		}
		//修改值
		const int cmask = (cols[c] << 1) + val;
		const int rmask = (rows[r] << 1) + val;
		if (r == N - 1) {
			if (hascol[cmask]) { return false; }
		}
		if (c == N - 1) {
			if (hasrow[rmask]) { return false; }
		}
		row1cnts[r] = row1;
		col1cnts[c] = col1;
		rows[r] = rmask;
		cols[c] = cmask;
		if (r == N - 1) {
			hascol[cmask] = true;
		}
		if (c == N - 1) {
			hasrow[rmask] = true;
		}
		//回溯
		int r1 = r;
		int c1 = c + 1;
		if (c1 >= N) {
			c1 = 0;
			r1++;
		}
		if (BackTrack(r1, c1)) { return true; }
		//恢复旧值
		row1cnts[r] -= (1 == val);
		col1cnts[c] -= (1 == val);
		rows[r] = rmask >> 1;
		cols[c] = cmask >> 1;
		if (r == N - 1) {
			hascol[cmask] = false;
		}
		if (c == N - 1) {
			hasrow[rmask] = false;
		}
		return false;
	};
	vector<int> row1cnts, col1cnts, rows, cols, hasrow, hascol;
	int N;
	vector<string> grid;
};

int main() {
#ifdef _DEBUG
	freopen("a.in", "r", stdin);
#endif // DEBUG	
	ios::sync_with_stdio(0); cin.tie(nullptr);
	//CInBuff<> in; COutBuff<10'000'000> ob;
	int N;
	cin >> N ;
	auto grid = Read<string>(N );	
#ifdef _DEBUG	
		printf("N=%d", N);
		//Out(c, ",c=");
		//Out(que, ",que=");
		Out(grid, ",grid=");
		//Out(edge2, ",edge2=");
		//Out(rr, ",rr=");
	   //Out(ab, ",ab=");
	   //Out(par, "par=");
	   //Out(que, "que=");
	   //Out(B, "B=");
#endif // DEBUG	
		Solution slu;
		auto res = slu.Ans(N, grid);
		for (const auto& s : res)
		{
			cout << s << "\n";
		}
	return 0;
};

单元测试

int N;
		vector<string> grid;
		TEST_METHOD(TestMethod00)
		{
			N = 6, grid = { "_0____","____01","__1__1","__1_0_","______","__1___" };
			auto res = Solution().Ans(N, grid);
			AssertV({ "100110","010101","001011","101100","110010","011001" }, 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++**实现。


网站公告

今日签到

点亮在社区的每一天
去签到