1131 Subway Map (30 point(s))

题解

spfa可以解,但是比较麻烦。最好还是暴力dfs.

以下题解少考虑了情况,Pat给的测试数据还是太少了,所以过了。

#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
#include<queue>
using namespace std;
const int MAXN = 1e4;
const int INF = 0x3f3f3f3f; 
vector<int> e[MAXN], line[MAXN];
int preLine[MAXN], pre[MAXN], dis[MAXN], cnt[MAXN], vis[MAXN];
int n, m, k, a, b;
void solve(int s, int t) {
	fill(dis, dis + MAXN, INF);
	fill(cnt, cnt + MAXN, INF);
	fill(vis, vis + MAXN, false);
	dis[s] = 0;
	cnt[s] = 0;
	queue<int> q;
	q.push(s);
	while(!q.empty()) {
		int u = q.front(); q.pop();
		vis[u] = false;
		for(int i = 0; i < e[u].size(); ++i) {
			int v = e[u][i], l = line[u][i];
			if(dis[v] > dis[u] + 1) {
				dis[v] = dis[u] + 1;
				pre[v] = u;
				preLine[v] = l;
				cnt[v] = cnt[u];
				if(preLine[u] != l) ++cnt[v];
				if(!vis[v]) {
					q.push(v); 
					vis[v] = true;
				}
			} else if(dis[v] == dis[u] + 1) {
				int d = cnt[u];
				if(preLine[u] != l) ++d;
				if(d <= cnt[v]) { // 这个地方是不准确的 
					pre[v] = u;
					preLine[v] = l;
					cnt[v] = d;
					if(!vis[v]) {
						q.push(v); 
						vis[v] = true;
					}
				}
			}
		}
	}
	printf("%d\n", dis[t]);
	int curLine = preLine[t], cur = t;
	for(int i = t; i != s; i = pre[i]) {
		if(preLine[i] != curLine) {
			printf("Take Line#%d from %04d to %04d.\n", curLine, cur, i);
			curLine = preLine[i];
			cur = i;
		}
	}
	printf("Take Line#%d from %04d to %04d.\n", curLine, cur, s);
}
int s, t;
int main() {
	scanf("%d", &n);
	for(int i = 1; i <= n; ++i) {
		scanf("%d%d", &m, &a);
		for(int j = 1; j < m; ++j) {
			scanf("%d", &b);
			e[a].push_back(b); e[b].push_back(a);
			line[a].push_back(i); line[b].push_back(i); 
			a = b;
		}
	}
	scanf("%d", &k);
	for(int i = 0; i < k; ++i) {
		scanf("%d%d", &s, &t);
		solve(t, s);
	}
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值