C++笔试强训day27

目录

1.kotori和气球

2.走迷宫

3.主持人调度(二)


1.kotori和气球

链接

数学找规律题,注意每次更新ret后判断是否 > 109,如果大于就取模。

#include <iostream>

using namespace std;

int n, m;
int main()
{
    cin >> n >> m;

    int ret = n;
    for (int i = 1; i < m; ++i)
    {
        ret *= n - 1;
        if (ret > 109)
            ret %= 109;
    }
    cout << ret << endl;
    return 0;
}

2.走迷宫

链接

经典的利用BFS找迷宫中的最短路径:

#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int N = 1010;
int dx[4] = { 0, 0, 1, -1 };
int dy[4] = { 1, -1, 0, 0 };
int n, m;
int x1, y1, x2, y2;
char arr[N][N];
int dist[N][N]; // [i, j] 位置是否已经搜索过,以及到达 [i, j] 位置的最短距离
int bfs()
{
	if (arr[x2][y2] == '*') return -1;

	memset(dist, -1, sizeof dist); // 表⽰还没开始搜索
	queue<pair<int, int>> q;
	q.push({ x1, y1 });
	dist[x1][y1] = 0;
	while (q.size())
	{
		auto [a, b] = q.front();
		q.pop();
		for (int i = 0; i < 4; i++)
		{
			int x = a + dx[i], y = b + dy[i];
			if (x >= 1 && x <= n && y >= 1 && y <= m && arr[x][y] == '.' &&
				dist[x][y] == -1)
			{
				q.push({ x, y });
				dist[x][y] = dist[a][b] + 1;
				if (x == x2 && y == y2) return dist[x2][y2];
			}
		}
	}
	return -1;
}
int main()
{
	cin >> n >> m >> x1 >> y1 >> x2 >> y2;
	for (int i = 1; i <= n; i++)
	{
		for (int j = 1; j <= m; j++)
		{
			cin >> arr[i][j];
		}
	}
	cout << bfs() << endl;
	return 0;
}

注意:
第一次到达终点时肯定是最近的,直接return即可。

3.主持人调度(二)

链接

优先级队列解法(注意,以主持人的结束时间作为根据建立小根堆)

class Solution
{
public:
    int minmumNumberOfHost(int n, vector<vector<int> >& startEnd)
    {
        sort(startEnd.begin(), startEnd.end());

        // 创建⼀个⼩根堆
        priority_queue<int, vector<int>, greater<int>> heap; 

        // 先把第⼀个区间放进去
        heap.push(startEnd[0][1]); 

        // 处理剩下的区间
        for (int i = 1; i < n; i++) 
        {
            int a = startEnd[i][0], b = startEnd[i][1];
            if (a >= heap.top()) // 没有重叠
            {
                heap.pop();
                heap.push(b);
            }
            else // 有重叠
            {
                heap.push(b); // 重新安排⼀个⼈
            }
        }
        return heap.size();
    }
};
  • 12
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值