HDU1548【Dijkstra和BFS】

传送门:http://acm.hdu.edu.cn/showproblem.php?pid=1548

【广搜BFS分析】有N层楼,每层只能上或者下Ni阶,但是不能低于一层或高于N层,所以,每一次往两个方向搜索。

#include
#include
#include
#include
#include
using namespace std;


int step[205];
int vis[205];
int a[205];
int main()
{
	int n;
	while (scanf("%d", &n) && n)
	{
		int s, e;
		scanf("%d%d", &s, &e);
		memset(vis, 0, sizeof(vis));
		memset(step, 0, sizeof(step));
		for (int i = 1; i <= n; i++)
			scanf("%d", &a[i]);
		queueq;
		vis[s] = 1;
		step[s] = 0;
		q.push(s);
		int flag = 0;
		while (!q.empty())
		{
			int temp = q.front();
			q.pop();
			if (temp == e)
			{
				printf("%d\n", step[temp]);
				flag = 1;
				break;
			}
		
			for (int i = 0; i < 2; i++)
			{
				int next;
				if (i == 0)
					next = temp + a[temp];
				else
					next = temp - a[temp];
				if (next<1 || next>n)
					continue;
				if (!vis[next])
				{
					q.push(next);
					step[next] = step[temp]+1;
					vis[next] = 1;
				}
			}
		}
		if (flag == 0)
			printf("-1\n");
	}
	return 0;
}

【Dijkstra分析】用二维数组,从储存图,把 i 到 j 的点map[i][j]记为1,因为直接步数为1。

#include
#include
#include
#include
#include
using namespace std;
int map[205][205];
int dist[205];
int s[205];
int a[205];
int n;//层数
int ss, ee;//起点和终点
const int M = 0x3f3f3f3f;
void Dijkstra();
int main()
{
	while (scanf("%d", &n) && n)
	{
		scanf("%d%d", &ss, &ee);
		for (int i = 1; i <= n; i++)
		{
			for (int j = 1; j <= n; j++)
			{
				if (i != j)
					map[i][j] = M;
				else
					map[i][j] = 0;
			}
		}
		for (int i = 1; i <= n; i++)
		{
			scanf("%d", &a[i]);
			if (i + a[i] <= n)
				map[i][i + a[i]] = 1;
			if (i - a[i] > 0)
				map[i][i - a[i]] = 1;
		}
		Dijkstra();
	}

	return 0;
}
void Dijkstra()
{
	for (int i = 1; i <= n; i++)
	{
		s[i] = 0;
		dist[i] = map[ss][i];
	}
	dist[ss] = 0;
	s[ss] = 1;
	for (int i = 1; i <= n - 1; i++)
	{
		int min = M;
		int k = ss;
		for (int j = 1; j <= n; j++)
		{
			if (!s[j] && dist[j] < min)
			{
				min = dist[j];
				k = j;
			}
		}
		s[k] = 1;
		for (int j = 1; j <= n; j++)
		{
			if (!s[j] && map[k][j]dist[k] + map[k][j])
				dist[j] = dist[k] + map[k][j];
		}
	}
	if (dist[ee] != M)
		printf("%d\n", dist[ee]);
	else
		printf("-1\n");
}

 

 

 

 

 

你可能感兴趣的:(做题记录)