例题7-15(uva-1603)

这篇博客探讨了一个关于火柴的游戏问题,其中玩家需要移除火柴以消除正方形。博主首先介绍了问题背景,然后展示了如何初始化游戏状态,包括火柴数量、矩阵表示以及正方形计数。接下来,通过深度优先搜索算法来寻找最少移除火柴的数量。博客内容涉及到数据结构和算法的应用,特别是搜索策略在解决这类问题上的有效性。
#include <iostream>
#include <istream>
#include <sstream>
#include <vector>
#include <stack>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <cstring>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <numeric>
#include <chrono>
#include <ctime>
#include <cmath>
#include <cctype>
#include <string>
#include <cstdio>
#include <iomanip>


#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <iterator>
using namespace std;
const int maxn = 64;
const int maxm = 64;

char matchs[maxn];
int	 actCnt[maxm], allCnt[maxm], matrix[maxm][maxn], n, k,cnt,ret;

int GetRowID(int x,int y)
{
	return (2 * n + 1)*x + y;
}

int GetColID(int x,int y)
{
	return (2 * n + 1)*x + n + y;
}

int GetNext()
{
	for (int i = 0; i < cnt; i++){
		if (actCnt[i] == allCnt[i]) return i;
	}
	return -1;
}

void Init()
{
	int id,temp;
	cin >> n;
	memset(matchs, 0x01, sizeof(matchs));
	memset(matrix, 0, sizeof(matrix));

	//最少拿走的火柴数
	ret = n * n;

	cin >> temp;
	//去掉当前id的火柴
	for (int i = 0; i < temp; i++){
		cin >> id;
		matchs[id - 1] = 0;
	}
	//包含的正方形个数
	cnt = 0;
	//多大的正方形
	for (int size = 1; size <= n; size++){
		//从x行y列的正方形开始
		for (int x = 0; x <= n - size; x++){
			for (int y = 0; y <= n - size; y++){
				//当前正方形实际包含的火柴数
				actCnt[cnt] = 0;
				//当前完整的正方形包含的火柴数
				allCnt[cnt] = size * 4;

				//标记对应的火柴属于第几个正方形
				//扩展边界直到大小为size
				for (int t = 0; t < size; t++){
					int a = GetRowID(x,y + t);
					int b = GetRowID(x+size,y+t);
					int c = GetColID(x+t,y);
					int d = GetColID(x+t,y+size);
					matrix[cnt][a] = 1;
					matrix[cnt][b] = 1;
					matrix[cnt][c] = 1;
					matrix[cnt][d] = 1;
					actCnt[cnt] += matchs[a] + matchs[b] + matchs[c] + matchs[d];
				}
				++cnt;
			}
		}
	}
}

void dfs(int depth)
{
	if (depth >= ret) return;

	int id = GetNext();
	if (id == -1) {
		ret = min(depth, ret);
		return;
	}

	for (int i = 0; i < maxn; i++){
		if (matrix[id][i]) {
			for (int j = 0; j < cnt; j++)
				if (matrix[j][i]) actCnt[j]--;
			dfs(depth + 1);
			for (int j = 0; j < cnt; j++)
				if (matrix[j][i]) actCnt[j]++;
		}
	}
}

int main()
{
	int m;
	cin >> m;
	while (m--){
		Init();
		dfs(0);
		cout << ret << endl;
	}
	return 0;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值