UVA Live 7693 (Codeforces Gym 101201B) Buggy Robot DP+bfs

https://vjudge.net/contest/179241#problem/B


给你一个地图,机器人从起点到终点按照字符串的指示前进,如果遇到障碍或者出边界就停留在原地,不算违规。

问你最少修改字符串的几个字符,才能让机器人到终点。


用dp[i][j][k]表示扫描完前k个字符之后,到达地图坐标(i,j)上的最小代价。

把每个状态都依次穷举,加入队列后bfs。


#include <cstdio>
#include <iostream>
#include <string.h>
#include <string> 
#include <map>
#include <queue>
#include <vector>
#include <set>
#include <algorithm>
#include <math.h>
#include <cmath>
#include <stack>
#define mem0(a) memset(a,0,sizeof(a))
#define meminf(a) memset(a,0x3f,sizeof(a))
using namespace std;
typedef long long ll;
typedef long double ld;
const int maxn=55,inf=0x3f3f3f3f;  
const ll llinf=0x3f3f3f3f3f3f3f3f;   
const ld pi=acos(-1.0L); 
int dp[maxn][maxn][maxn];
int mp['Z'+1];
char a[maxn][maxn],s[maxn];
int n,m;

struct node {
	int x,y,pos;
	node (int x,int y,int pos):x(x),y(y),pos(pos){}
};

bool check(int i,int j) {
	return i>0&&i<=n&&j>0&&j<=m&&a[i][j]!='#';
}

int main() {
//	freopen("F.in","r",stdin);
//	freopen("F.out","w",stdout);
	int i,j,sx,sy,tx,ty;
	int dir[4][2]={{0,1},{0,-1},{-1,0},{1,0}}; 
	mp['R']=0;mp['L']=1;mp['U']=2;mp['D']=3;
	queue<node> q;
	scanf("%d%d",&n,&m);
	for (i=1;i<=n;i++) {
		scanf("%s",a[i]+1);
		for (j=1;j<=m;j++) {
			if (a[i][j]=='R') sx=i,sy=j;
			if (a[i][j]=='E') tx=i,ty=j;
		}
	}
	scanf("%s",s+1);
	int len=strlen(s+1);
	meminf(dp);
	dp[sx][sy][0]=0;
	q.push(node(sx,sy,0));
	while (!q.empty()) {
		node now=q.front();
//		cout << now.x << ' ' << now.y << ' ' << now.pos << " " <<
//		dp[now.x][now.y][now.pos] << endl;
		q.pop();
		//在pos处添加一个字符 
		for (i=0;i<4;i++) {
			int nowx=now.x+dir[i][0],nowy=now.y+dir[i][1];
			if (check(nowx,nowy))
			if (dp[nowx][nowy][now.pos]>dp[now.x][now.y][now.pos]+1) {
				dp[nowx][nowy][now.pos]=dp[now.x][now.y][now.pos]+1;
				q.push(node(nowx,nowy,now.pos));
			}
		} 
		if (now.pos<len) {
			//在pos处删除一个字符 
			if (dp[now.x][now.y][now.pos+1]>dp[now.x][now.y][now.pos]+1) {
				dp[now.x][now.y][now.pos+1]=dp[now.x][now.y][now.pos]+1;
				q.push(node(now.x,now.y,now.pos+1));
			}
			//按照原字符串pos位的字符行走 
			int nowx=now.x+dir[mp[s[now.pos+1]]][0],
			nowy=now.y+dir[mp[s[now.pos+1]]][1];
			if (!check(nowx,nowy)) nowx=now.x,nowy=now.y;
			if (dp[nowx][nowy][now.pos+1]>dp[now.x][now.y][now.pos]) {
				dp[nowx][nowy][now.pos+1]=dp[now.x][now.y][now.pos];
				q.push(node(nowx,nowy,now.pos+1));
			}
		}
	}
	int ans=inf;
	for (i=0;i<=len;i++) {
		ans=min(ans,dp[tx][ty][i]);
	}
	printf("%d\n",ans);
	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值