NEUQ-ACM预备队必做题——第六周

洛谷P1135 奇怪的电梯

思路:

应该基本是bfs模板题。多次搜索,搜到即退出,得到最少次数。

代码:

#include <iostream>
#include <queue>
using namespace std;
const int N = 210;
int k[N], n, a, b;
bool st[N];
int dist[N];

int bfs(int a)
{
	queue<int> q;
	q.push(a);
	st[a] = true;
	dist[a] = 0;
	while(q.size()>0)
	{
		int t = q.front();
		q.pop();
		
		if (t == b)return dist[t];
		
		//上去
		if (t + k[t] <= n)
		{
			int tem = t + k[t];
			if (!st[tem])
			{
				q.push(tem);
				st[tem] = true;
				dist[tem] = dist[t] + 1;
			}
		}
		
		if (t - k[t] >= 1)
		{
			int tem = t - k[t];
			if(!st[tem])
			{
				q.push(tem);
				st[tem] = true;
				dist[tem] = dist[t] + 1;
			}
		}
	}
	return -1;
}

int main()
{
	cin >> n >> a >> b;
	
	for (int i = 1; i <= n; i ++ )
		cin >> k[i];
		
	int t = bfs(a);
	if (t == -1) cout << -1 << endl;
	else cout << t << endl;
	
	return 0;
}

洛谷P1443 马的遍历

思路:

八个方向走,也基本是模板题

代码:

#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
typedef pair<int, int> PII;
const int N = 410;

int n, m, x, y;
int dx[8] = {1,1,-1,-1,2,2,-2,-2}, dy[8] = {2,-2,2,-2,1,-1,1,-1};
int dist[N][N];
bool st[N][N];

void bfs()
{
	queue<PII> q;
	q.push({x,y});
	st[x][y] = true;
	dist[x][y] = 0;
	
	while(q.size()>0)
	{
		PII t = q.front();
		q.pop();
		int tx = t.first, ty = t.second;
		for (int i = 0; i < 8; i ++)
		{
			int xx = tx + dx[i], yy = ty + dy[i];
			if(xx>=1 && xx<=n && yy>=1 && yy<=m)
			{
				if(!st[xx][yy])
				{
					q.push({xx,yy});
					dist[xx][yy] = dist[tx][ty] + 1;
					st[xx][yy] = true;
				}
			}
		}
	}
	return ;
}

int main()
{
	cin >> n >> m >> x >> y;
	
	memset (dist,-1,sizeof dist);
	
	bfs();
	
	for (int i = 1; i <= n; i ++ )
	{
		for (int j = 1; j <= m; j ++ )
		{
			cout << dist[i][j] << ' ';
		}
		puts("");
	}
	
	return 0;
}

洛谷P1162 填涂颜色

思路:

这个一开始不会写,后来看了题解,然后自己发现有点dfs的意思,感觉没有用到bfs

代码:

#include <iostream>
using namespace std;
const int N = 35;

int map[N][N],n;
int dx[4] = {1,-1,0,0},dy[4] = {0,0,1,-1};

void dfs(int x, int y)
{
	for (int i = 0; i <= 4; i ++ )
	{
		int xx = x + dx[i], yy = y + dy[i];
		if (xx >= 0 && xx <= n+1 && yy >= 0 && yy <= n+1)
		{
			if (map[xx][yy] == 0)
			{
				map[xx][yy] = 2;
				dfs(xx,yy);
			}
		}
	}
}

int main()
{
	cin >> n;
	for (int i = 1; i <= n; i ++ )
	{
		for (int j = 1; j <= n; j ++ )
		{
			cin >> map[i][j];
		}
	}
	
	dfs(0,0);
	
	for (int i = 1; i <= n; i ++)
	{
		for (int j = 1; j <= n; j ++)
		{
			if(map[i][j] == 0) cout << 2 << ' ';
			else if (map[i][j] == 2) cout << 0 << ' ';
			else cout << map[i][j] << ' ';
		}
		puts("");
	}
	return 0;
}

最近又有比赛又有考试,实在没时间,所以第三题没写。下次再补…

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值