POJ 1847 Tram 优先队列+bfs

来源:http://poj.org/problem?id=1847

题意:在一个地方,有一些调度站,这些调度站和其他一些调度站之间有路。但是一个调度站只和另一个调度站直接相连,另外和一些调度站间接相连。如果从该调度站到达其直接相连的调度站需要0步,到达其间接相连的调度站需要1步。现在给出了起点和终点,问从起点到终点最少需要多少步。

思路:很明显用bfs可以解决了,但因为涉及到步数增加不一致的问题,所以可以用优先队列做。其实和 POJ 2312是一样的。

代码:

#include <iostream>
#include <cstdio>
#include <string.h>
#include <queue>
#include <vector>
using namespace std;

#define CLR(arr,val) memset(arr,val,sizeof(arr))
struct station{
	int id,step;
	bool operator < (const station & a)const{
		return step > a.step;
	}
};
const int N = 110;
int map[N][N],flag[N],n,spos,epos;
bool vis[N][N];
vector<int> vv[N];
int bfs(){
	priority_queue<station> qq;
	station s;
	s.id = spos;
	s.step = 0;
	flag[spos] = 1;
	qq.push(s);
	while(!qq.empty()){
	  station ts = qq.top();
	  //printf("ts.id = %d\n",ts.id);
	  //printf("ts.step = %d\n",ts.step);
	  qq.pop();
	  if(ts.id == epos){
		  return ts.step;
	  }
	  else{
		  for(int i = 0; i < vv[ts.id].size(); ++i){
		     int y = vv[ts.id][i];
			 if(vis[ts.id][y]){
			    vis[ts.id][y] = 0;
				station news;
				news.id = y;
				if(map[ts.id][y] == 1){
					//printf("y = %d\n",y);
					news.step =  ts.step;
				}
				else{
					news.step = ts.step + 1;
				}
				qq.push(news);
			 }
		  }
	  }
	}
	return -1;
}
int main(){
	//freopen("1.txt","r",stdin);
	while(scanf("%d%d%d",&n,&spos,&epos) != EOF){
	   int num,x;
	   CLR(map,0);
	   CLR(flag,0);
	   CLR(vv,0);
	   CLR(vis,0);
	   for(int i = 1; i <= n; ++i){
	     scanf("%d",&num);
		 for(int j = 1;j <= num; ++j){
		   scanf("%d",&x);
		   vv[i].push_back(x);
		   vis[i][x] = 1;
		   if(j == 1)
			   map[i][x] = 1;
		   else
			   map[i][x] = 2;
		 }
	   }
	   int ans = bfs();
	   printf("%d\n",ans);
	}
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值