搜索专题 (DFS, BFS)

回溯法

  • 回溯法:带限界函数的深度优先搜索

0-1 背包问题

void DFS(int index, int sumW, int sumC) {
	if (index == n) {
		return; // 已经完成对 n 件物品的选择
	}
	DFS(index + 1, sumW, sumC); 	// 不选第 index 件物品
	// 只有加入第 index 件物品后未超过容量 V, 才能继续
	if (sumW + w[index] <= Y) {
		if(sumC + c[index] > ans) {
			ans = sumC + c[index]; // 更新最大价值 maxValue
		}
		DFS(index + 1, sumW + w[index], sumC + c[index]); // 选第index件物品
	}
}
  • 上面只是示例,如果想进一步优化,可以针对不选第 index 件物品的情况添加限界函数 (例如可以利用贪心思想,拿剩余物品中价值最高的按比例放进背包里,得到一个上界函数,只有当这个上界函数大于目前找的的最优解时才继续搜索)

  • 再例如这样一个问题:给定 N N N 个整数,从中选择 K K K 个数, 使得这 K K K 个数之和恰好等于一个给定的整数 X X X; 如果有多种方案, 选择它们中元素平方和最大的一个。数据保证这样的方案唯一
// 序列 A 中 n 个数选 k 个数使得和为 X, 最大平方和为 maxSumSqu
int n, k, x, maxSumSqu = -1, A[maxn];
// temp 存放临时方案,ans 存放平方和最大的方案
vector<int> temp, ans;
// 当前处理 index 号整数,当前已选整数个数为 nowK
// 当前已选整数之和为sum, 当前已选整数平方和为 sumSqu
void DFS(int index, int nowK, int sum, int sumSqu)
{
	if (nowK == k && sum == x) { 
		if (sumSqu > maxSumSqu) {
			maxSumSqu = sumSqu; 
			ans = temp;
		}
		return;
	}
	// 约束函数
	if(index = n || nowK > k || sum > x) 
		return;
	// 选 index 号数
	temp.push_back(A[index]);
	DFS(index + 1, nowK + 1, sum + A[index], sumSqu + A[index] * A[index]);
	temp.pop_back();
	// 不选 index 号数
	// 同样的,这里也可以加上限界函数来剪枝
	DFS(index + 1, nowK, sum, sumSqu);
}

PAT (Advanced level) 1103 Integer Factorization

题目在此

  • 这种题关键还是看到题目之后确定使用回溯法;可能是我目前做这种题目还比较少,第一眼看到这个题目可能想不到用回溯法;但如果确定解法之后还是比较好解决的
#include <cstdio>
#include <vector>
#include <cmath>

using namespace std;

int MaxSum = -1;
int N, K, P;
vector<int> best;

int MaxFactor;

void DFS(int k, vector<int>& tmp, int sum_pow, int sum)
{
	if (k == K)
	{
		if (sum_pow == N)	// one solution
		{
			bool update_flag = false;
			if (sum > MaxSum)
			{
				update_flag = true;
			}
			// 由于是从大到小选数字,因此这里不用判断;早选出来的解字典序一定是更大的
			//else if (sum == MaxSum && tmp >= best)
			//{
			//	update_flag = true;
			//}
			if (update_flag)
			{
				best = tmp;
				MaxSum = sum;
			}
		}
		return;
	}
	
	// 选出解的规则为由大到小选
	int max_element = MaxFactor;
	if (k != 0)
	{	// tmp 中已选出若干元素
		max_element = tmp.back();
	}
	// 约束函数: 幂和超过 N 或 不可能达到 N 的均剪枝
	if (sum_pow >= N || sum_pow + (N - k) * (int)pow(max_element, P) < N)
	{
		return;
	}
	
	for (int i = max_element; i >=1; --i)
	{
		int pow_i = (int)pow(i, P);
		if (sum_pow + pow_i <= N	// 约束函数
			&& sum + i + max(N - k - 1, 0) * max_element >= MaxSum		// 限界函数
			)
		{	// choose i
			tmp.push_back(i);
			DFS(k + 1, tmp, sum_pow + pow_i, sum + i);
			tmp.pop_back();
		}
	}
}

int main(void)
{
	scanf("%d %d %d", &N, &K, &P);
	MaxFactor = (int)sqrt(N);	// p >= 2
	vector<int> tmp;
	DFS(0, tmp, 0, 0);

	if (best.size() == 0) {
		printf("Impossible");
	}
	else {
		printf("%d = %d^%d", N, best[0], P);
		for (int i = 1; i != K; ++i)
		{
			printf(" + %d^%d", best[i], P);
		}
	}

	return 0;
};

BFS

void BFS(int s) {
	queue<int> q;
	q.push(s);
	while (!q.empty()) {
		int node = q.front();
		visit(node);
		q.pop();
		for(node 的下一层结点中所有未曾入队的结点) {
			q.push(next_node);
			inq[next_node] = true;
		}
	}
}
  • 注意:一定是在入队之后设置标识为真,而非访问之后再设置;否则可能在某个结点正在队列中时由于其他结点可以到达它而将这个结点再次入队, 导致很多结点反复入队,计算量大大增加
  • 如果要对队列中的元素进行修改而不仅仅是访问时, 队列中存放的元素最好不要是元素本身, 而是它们的编号(如果是数组的话则是下标)

  • 给出一个 m × n m\times n m×n 的矩阵,矩阵中的元素为 0 或 1。如果矩阵中有若干个 1 是相邻的(不必两两相邻), 那么称这些 1 构成了一个 “块”。求给定的矩阵中 “块” 的个数
// 4 个块
0 1 1 1 0 0 1
0 0 1 0 0 0 0
0 0 0 0 1 0 0
0 0 0 1 1 1 0
1 1 1 0 1 0 0
1 1 1 1 0 0 0
  • Tip:对当前位置 ( x , y ) (x,y) (x,y) 来说, 由于与其相邻的四个位置分别为 ( x , y + 1 ) (x,y + 1) (x,y+1), ( x , y − 1 ) (x,y-1) (x,y1), ( x + 1 , y ) (x+1,y) (x+1,y), ( x − 1 , y ) (x- 1,y) (x1,y), 那么不妨设置两个增量数组,来表示四个方向
int X[] = { 0, 0, 1, -1};
int Y[] = { 1, -1, 0, 0};
for(int i = 0; i < 4; i++)
{
	nowX = nowX + X[i];
	nowY = nowY + Y[i];
}
#include <cstdio>
#include <queue>
using namespace std;
const int maxn = 100;
struct node {
	int x, y;
} Node;

int n, m;	// 矩阵大小为 n x m
int matrix[maxn][maxn];
bool inq[maxn][maxn] = {false}; // 记录位置(x, y)是否已入过队
int X[4] = {0, 0, 1, -1}; // 增量数组
int Y[4] = {1, -1, 0, 0};

bool judge(int x, int y) {	// 判断 (x,y) 是否需要访问
	// 越界判断
	if (x >= n || x < 0 || y >= m || y < 0) 
		return false;
	if (matrix[x][y] == 0 || inq[x][y] == true) 
		return false;
		
	return true;
}

// BFS 函数访问位置 (x, y) 所在的块, 将该块中所有 "1" 的 inq 都设置为 true
void BFS(int x, int y) {
	queue<node> Q;
	Node.x = x, Node.y = y; // 当前结点的坐标为(x, y)
	Q.push(Node);
	inq[x][y] = true;
	
	while (!Q.empty()) {
		node top = Q.front();
		Q.pop(); 
		for(int i = 0; i < 4; i++) {
			int newX = top.x + X[i];
			int newY = top.y + Y[i];
			if (judge(newX, newY)) {
				Node.x = newX, Node.y = newY;
				Q.push(Node);
				inq[newX][newY] = true;
			}
		}
	}
}

int main()
{
	scanf("%d%d", &n, &m);
	for(int x = 0; x < n; x++)
		for(int y = 0; y < m; y++)
			scanf("%d", &matrix[x][y]);
	
	int ans = 0; // 存放块数
	for(int x = 0; x < n; x++) {
		for(int y = 0; y < m; y++) {
			// 如果元素为 1, 且未入过队
			if(matrix[x][y] == 1 && inq[x][y] == false) {
				ans++;
				BFS(x, y);
			}
		}
	}
	printf("%d\n", ans);
	return 0;
}

PAT (Advanced level) 1091 Acute Stroke

题目在此

  • 注意点:本题使用 DFS 非常容易在最后两组数据中出现段错误, 原因是当三维矩阵中所有元素均为 1 时, DFS 的深度过深, 会使系统栈达到上限, 从而爆栈
#include <cstdio>
#include <queue>

using namespace std;

int M, N, L, T;
vector<vector<vector<int>>> Img;
vector<vector<vector<bool>>> InQ;
int Volume = 0;

// 上、下、前、后、左、右
int Z[] = { -1, 1, 0, 0, 0, 0 };
int X[] = { 0, 0, 0, 0, -1, 1 };
int Y[] = { 0, 0, -1, 1, 0, 0 };

struct Node {
	int z;
	int x;
	int y;
};

bool valid_pos(Node& node)
{
	int layer = node.z, x = node.x, y = node.y;
	if (layer >= 0 && layer < L
		&& x >= 0 && x < M
		&& y >= 0 && y < N
		&& InQ[layer][x][y] == false
		&& Img[layer][x][y] == 1)
	{
		return true;
	}
	return false;
}

int BFS(Node node)
{
	queue<Node> q;
	q.push(node);
	InQ[node.z][node.x][node.y] = true;
	int cnt = 1;
	while (!q.empty())
	{
		Node node = q.front();
		q.pop();
		for (int i = 0; i != 6; ++i)
		{
			Node new_node = { node.z + Z[i], node.x + X[i], node.y + Y[i] };
			if (valid_pos(new_node))
			{
				q.push(new_node);
				++cnt;
				InQ[new_node.z][new_node.x][new_node.y] = true;
			}
		}
	}
	return (cnt >= T) ? cnt : 0;
}

int main(void)
{
	scanf("%d %d %d %d", &M, &N, &L, &T);
	Img.resize(L);
	InQ.resize(L);
	
	for (int layer = 0; layer != L; ++layer)
	{
		Img[layer].resize(M);
		InQ[layer].resize(M);
		for (int i = 0; i != M; ++i)
		{
			Img[layer][i].resize(N);
			InQ[layer][i].resize(N);
			for (int j = 0; j != N; ++j)
			{
				scanf("%d", &Img[layer][i][j]);	
				InQ[layer][i][j] = false;
			}
		}
	}

	for (int layer = 0; layer != L; ++layer)
	{
		for (int i = 0; i != M; ++i)
		{
			for (int j = 0; j != N; ++j)
			{
				if (InQ[layer][i][j] == false && Img[layer][i][j] == 1)
				{
					Volume += BFS({ layer, i, j });
				}
			}
		}
	}
	printf("%d", Volume);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值