【YBTOJ进阶训练指导】最小权值【广搜】

26 篇文章 0 订阅
18 篇文章 0 订阅

在这里插入图片描述

思路:

最大值的最小值,考虑二分答案
二分上限,bfs判断可达性

c o d e code code

#include<iostream>
#include<cstdio>
#include<queue>

using namespace std;

int n, m;
int a[1010][1010], b[1010][1010];
int dx[4]={0, 1, 0, -1};
int dy[4]={1, 0, -1, 0};

bool check(int maxx)
{
	queue<pair<int, int> > q;
	for(int i=1; i<=n; i++)
		for(int j=1; j<=m; j++)
			if(a[i][j]>maxx)
				b[i][j]=-1;
			else b[i][j]=0;
	for(int j=1; j<=m; j++)
		if(b[1][j]==0)
			q.push(make_pair(1, j)), b[1][j]=-1;
	while(!q.empty())
	{
		int x=q.front().first, y=q.front().second;
		q.pop();
		for(int i=0; i<4; i++)
		{
			int xx=x+dx[i], yy=y+dy[i];
			if(xx<1||xx>n||yy<1||yy>n||b[xx][yy]==-1)
				continue;
			q.push(make_pair(xx, yy));
			b[xx][yy]=-1;
			if(xx==n)
				return 1;
		}
	}
	return 0;
}

int main()
{
	scanf("%d%d", &n, &m);
	for(int i=1; i<=n; i++)
		for(int j=1; j<=m; j++)
			scanf("%d", &a[i][j]);
	int l=0, r=1000, ans=1e9;
	while(l<=r)
	{
		int mid=l+r>>1;
		if(check(mid))
			r=mid-1, ans=min(ans, mid);
		else l=mid+1;
	}
	printf("%d", ans);
	return 0;
} 
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用C++类实现哈夫曼树最小权值和的示例代码: ``` #include <iostream> #include <queue> using namespace std; class Node { public: int weight; Node* left; Node* right; Node(int w) { weight = w; left = nullptr; right = nullptr; } ~Node() { delete left; delete right; } }; class Compare { public: bool operator()(Node* a, Node* b) { return a->weight > b->weight; } }; int huffman(Node* root, int depth) { if (root->left == nullptr && root->right == nullptr) { return root->weight * depth; } int sum = 0; if (root->left != nullptr) { sum += huffman(root->left, depth + 1); } if (root->right != nullptr) { sum += huffman(root->right, depth + 1); } return sum; } int main() { int n; cin >> n; priority_queue<Node*, vector<Node*>, Compare> pq; for (int i = 0; i < n; i++) { int w; cin >> w; pq.push(new Node(w)); } while (pq.size() > 1) { Node* left = pq.top(); pq.pop(); Node* right = pq.top(); pq.pop(); Node* parent = new Node(left->weight + right->weight); parent->left = left; parent->right = right; pq.push(parent); } Node* root = pq.top(); int ans = huffman(root, 0); cout << ans << endl; delete root; return 0; } ``` 在这个示例中,我们定义了一个`Node`类来表示哈夫曼树的节点,其中包含权值、左子节点和右子节点。我们还定义了一个`Compare`类来实现节点的比较,用于构建哈夫曼树的优先队列。`huffman`函数用于计算哈夫曼树的最小权值和,它使用递归来遍历整棵树,计算每个叶子节点的权值和深度的乘积。 在`main`函数中,我们首先读入节点的数量和权值,然后使用优先队列来构建哈夫曼树。最后,我们计算哈夫曼树的最小权值和并输出结果。需要注意的是,在程序结束时,我们需要手动删除根节点来释放内存。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值