HDU 1428 漫步校园 SPFA + DFS记忆搜索

41 篇文章 0 订阅
12 篇文章 0 订阅

类似上题。

#include <stdio.h>
#include <string.h>
#define inf 0x7fffffff
struct
{
	int v, pow, next;
}edge[52*52*4];
int n = 0, map[52][52], head[52*52], dis[52*52], dir[4][2] = {{-1, 0}, {0, -1}, {0, 1}, {1, 0}};
__int64 choise[52][52];
void init()//建图
{
	int i = 0, j = 0, k = 0, x = 0, y = 0, count = 0;
	memset(head, -1, sizeof(head));
	for(i = 1; i<=n; i++)
	{
		for(j = 1; j<=n; j++)
		{
			for(k = 0; k<4; k++)
			{
				x = i+dir[k][0], y = j+dir[k][1];
				if(x>0 && x<=n && y>0 && y<=n)
				{
					edge[count].pow = map[i][j]+map[x][y];
					edge[count].v = (x-1)*n+y;
					edge[count].next = head[(i-1)*n+j];  //next域指向当前结点的前一条边,head指向最后一条边。邻接表表示
					head[(i-1)*n+j] = count++;
				}
			}
		}
	}
}
void spfa()
{
	int i = 0, p = 0, q = 0, row = 0, col = 0, front = 0, rear = 0, used[52*52], que[10000];
	for(i = 1; i<=n*n; i++)
	{
		used[i] = 0;
		dis[i] = inf;
	}
	dis[n*n] = map[n][n];
	used[n*n] = 1;
	que[rear++] = n*n;
	while(front != rear)
	{
		p = que[front];
		row = p%n == 0? p/n:p/n+1;//求在原图中的位置
		col = p%n == 0?  n:p%n;
		front = (front+1)%10000;
		used[p] = 0;
		for(q = head[p]; q != -1; q = edge[q].next)
		{
			if(dis[edge[q].v]>dis[p]+edge[q].pow-map[row][col])//多出的要减去
			{
				dis[edge[q].v] = dis[p]+edge[q].pow-map[row][col];
				if(used[edge[q].v] == 0)
				{
					used[edge[q].v] = 1;
					que[rear] = edge[q].v;
					rear = (rear+1)%10000;
				}
			}
		}
	}
}
__int64 dfs(int x, int y)//记忆搜索
{
	int i = 0, fx = 0, fy = 0;
	if(choise[x][y]>0) return choise[x][y];
	if(x == n && y == n) return 1;
	for(i = 0; i<4; i++)
	{
		fx = x+dir[i][0]; fy = y+dir[i][1];
		if(fx>0 && fx<=n && fy>0 && fy<=n)
		{
			if(dis[(fx-1)*n+fy]<dis[(x-1)*n+y])
			{
				choise[x][y] += dfs(fx, fy);
			}
		}
	}
	return choise[x][y];
}
int main()
{
	int i = 0, j = 0;
	while(scanf("%d",&n) != EOF)
	{
		for(i = 1; i<=n; i++)
			for(j = 1; j<=n; j++)
				scanf("%d",&map[i][j]);
		memset(choise, 0, sizeof(choise));
		init();
		spfa();
		choise[1][1] = dfs(1, 1);
		printf("%I64d\n",choise[1][1]);
	}
	return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值