PTA 1131 Subway Map (25/30 分)

https://pintia.cn/problem-sets/994805342720868352/problems/994805347523346432

题意:经过最少的站,如果经过的站数相同,那么换乘数量最少。

题解:我是用dijkstra的算法,记录路径,此节点的父节点和上一条线路。

但是始终只有25分。求大佬指点。

代码

#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int>pii;
int const N = 10000 + 10;
int const inf = 0x3f3f3f3f;
int n,k;
int last[N],fa[N],dis[N],num[N],vis[N];
struct Edge{
	int from,to,line;
	Edge(){};
	Edge(int a,int b,int c):from(a),to(b),line(c){};
}node[N];
vector<Edge>G[N];
priority_queue<pii,vector<pii>,greater<pii> >q;
vector<int>ans1,ans2;
void djikstra(int s,int t){
	for(int i=0;i<N;i++)	dis[i] = num[i] = inf,	fa[i] = 0,	last[i] = vis[i] = 0;
	dis[s] = 0,	num[s] = 0;
	q.push(pii(dis[s],s));
	last[s] = -1;  //表示上一条线路
  	fa[s] = -1;  //上一个结点
	while(!q.empty()){
		pii p = q.top();	q.pop();
		int from = p.second;
		if(vis[from])	continue;
		vis[from] = true;
		for(int i=0;i<G[from].size();i++){
			Edge e = G[from][i];
			if(dis[e.to] > dis[e.from] + 1){  //经过的节点数变少
				fa[e.to] = e.from;
				last[e.to] = e.line;
				dis[e.to] = dis[e.from] + 1;
				if(last[e.from] != e.line)	num[e.to] = num[e.from] + 1;  //换乘次数加1
				else	num[e.to] = num[e.from];
				q.push(pii(dis[e.to],e.to));
			}else if(dis[e.to] == dis[e.from] + 1){
				if(last[e.from] != e.line && num[e.to] > num[e.from] + 1){
					num[e.to] = num[e.from] + 1;
					fa[e.to] = e.from;	last[e.to] = e.line;
				}else if(last[e.from] == e.line && num[e.to] > num[e.from]){
					num[e.to] = num[e.from];
					fa[e.to] = e.from;	last[e.to] = e.line;
				}
			}
		}
	}
	ans1.clear();	ans2.clear();
	int f = t;
	int lastline = 0;
	int cnt = 0;
	while(f != -1){
		cnt++;	
		if(last[f] != lastline){
			ans1.push_back(f);
			lastline = last[f];
			ans2.push_back(lastline);
		}
		f = fa[f];
	}
	printf("%d\n",cnt - 1);
	int pos = ans2.size() - 2;
	for(int i=ans1.size()-1;i>=1;i--){
		printf("Take Line#%d from %04d to %04d.\n",ans2[pos--],ans1[i],ans1[i-1]);
	}
}
int main(){
	scanf("%d",&n);
	for(int i=1;i<=n;i++){
		int m;
		scanf("%d",&m);
		int a[105];
		for(int j=1;j<=m;j++)	scanf("%d",&a[j]);
		for(int j=1;j<m;j++){
			G[a[j]].push_back(Edge(a[j],a[j+1],i));
			G[a[j+1]].push_back(Edge(a[j+1],a[j],i));
		}
	}
	scanf("%d",&k);
	while(k--){
		int s,t;
		scanf("%d%d",&s,&t);
		djikstra(s,t);
	}
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值