hdu5025Saving Tang Monk 水bfs

真的是傻比到一定境界了,我居然没看到钥匙是按顺序拿的,还想着说把钥匙状压怎么破

不过这题交优先队列的时候不知道怎么tle了,用队列交反而过

有一点就是队列不一定一次就找得到最优解,所以要多次更新答案

#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
#include <cmath>
#include <vector>
#include <set>
#include <queue>
#include <map>
#include <cctype>
using namespace std;
#define INF 1e9
#define maxn
#define rep(i,x,y) for(int i=x;i<=y;i++)
#define mset(x) memset(x,0,sizeof(x))


int n, m, ans, scnt;
char mat[105][105];

struct node{
	int x, y, step, cnt, ss;
	node(){}
	node(int x, int y, int s, int c, int ss):x(x), y(y), step(s), cnt(c), ss(ss){}
	// bool operator< (const node& a)const {
	// 	return step>a.step;
	// }
}st;
int sx, sy;
queue<node> q;

bool vis[105][105][10][1<<6];
int dir[4][2] = {{1,0}, {-1,0}, {0,1}, {0,-1}};

bool reach(int x, int y){
	return (x>=0 && x<n && y>=0 && y<n && mat[x][y]!='#');
}

int bfs(){
	while(!q.empty())	q.pop();
	q.push(st);

	int ans = INF;
	while(!q.empty()){
		node u = q.front(); q.pop();
		if(mat[u.x][u.y]=='T' && u.cnt==m)
			ans = min(ans , u.step);

		if(vis[u.x][u.y][u.cnt][u.ss])
			continue;
		vis[u.x][u.y][u.cnt][u.ss] = 1;

		for(int i=0; i<4; i++)
		{
			int nx = u.x + dir[i][0];
			int ny = u.y + dir[i][1];
			if(!reach(nx, ny))	continue;

			if(mat[nx][ny]>='A' && mat[nx][ny]<='Z'){
				int k = mat[nx][ny]-'A';
				if(u.ss & (1<<k))	q.push( node(nx, ny, u.step+1, u.cnt, u.ss) );//如果已经杀过这条蛇了
				else	q.push( node(nx, ny, u.step+2, u.cnt, u.ss|(1<<k)) );
			}

			else if(mat[nx][ny]<='9' && mat[nx][ny]>='0'){
				int k = mat[nx][ny] - '0';
				if(k==u.cnt+1)	q.push( node(nx, ny, u.step+1, u.cnt+1, u.ss) );
				else q.push( node(nx, ny, u.step+1, u.cnt, u.ss) );
			}

			else	q.push( node(nx, ny, u.step+1, u.cnt, u.ss) );
		}
	}
	return ans;
}

int main(){
//	freopen("a.txt","r",stdin);
//	freopen(".out","w",stdout);
	while(cin>>n>>m){
		if(n==0 && m==0) break;

		mset(vis);
		scnt=0;
		for(int i=0; i<n; i++){;
			scanf("%s", mat[i]);
			for(int j=0; j<n; j++){
				if(mat[i][j]=='K'){
					sx=i, sy=j;
					mat[i][j] = '.';
				}
				if(mat[i][j]=='S'){
					mat[i][j] = 'A' + scnt;
					scnt++;
				}
			}
		}
		st = node(sx, sy, 0, 0, 0);
		int ans = bfs();
		if(ans==INF)	puts("impossible");
		else printf("%d\n", ans-1);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值