zoukankan      html  css  js  c++  java
  • 团体程序设计天梯赛 L3-007 天梯地图 (30分)(dijkstra变形)

    题目链接:

    L3-007 天梯地图 (30分)

    思路:

    这是PAT甲级原题…原本想直接复制之前的code,奈何博主觉得自己以前写的太乱了,遂重新写了一遍;
    这道题使用两次dijkstra即可,但是需要稍微改变一下,例如求最快最短的情况下,慢的需要更新为快的毋庸置疑,同时同样快的应该考虑路径长度是否需要更新;

    代码:

    #include<bits/stdc++.h>
    
    using namespace std;
    
    typedef pair<int, int> P;
    const int maxn = 505;
    const int INF = 1 << 30;
    struct edge { int to, len, tm; };
    int n, m, _s, _t, t[maxn], d[maxn], par[maxn], ans1[maxn], ans2[maxn];
    vector<edge> G[maxn];
    vector<int> route[2];
    
    void print_route(int u, int i) { if(u != _s) print_route(par[u], i); route[i].push_back(u); }
    void t_dijkstra() {
    	for(int i = 0; i < n; i++) t[i] = ans1[i] = INF;
    	t[_s] = ans1[_s] = 0;
    	priority_queue<P, vector<P>, greater<P> > que;
    	que.push(P(0, _s));
    	while(!que.empty()) {
    		P p = que.top(); que.pop();
    		int v = p.second;
    		if(t[v] < p.first) continue;
    		for(edge & e : G[v])
    			if(t[e.to] == t[v] + e.tm ? ans1[e.to] > ans1[v] + e.len : t[e.to] > t[v] + e.tm) {
    				par[e.to] = v, t[e.to] = t[v] + e.tm, ans1[e.to] = ans1[v] + e.len;
    				que.push(P(t[e.to], e.to));
    			}
    	}
    	print_route(_t, 0);
    }
    void d_dijkstra() {
    	for(int i = 0; i < n; i++) d[i] = ans2[i] = INF;
    	d[_s] = ans2[_s] = 0;
    	priority_queue<P, vector<P>, greater<P> > que;
    	que.push(P(0, _s));
    	while(!que.empty()) {
    		P p = que.top(); que.pop();
    		int v = p.second;
    		if(d[v] < p.first) continue;
    		for(edge & e : G[v])
    			if(d[e.to] == d[v] + e.len ? ans2[e.to] > ans2[v] + 1 : d[e.to] > d[v] + e.len) {
    				d[e.to] = d[v] + e.len, par[e.to] = v, ans2[e.to] = ans2[v] + 1;
    				que.push(P(d[e.to], e.to));	
    			}
    	}
    	print_route(_t, 1);
    }
    
    int main() {
    #ifdef MyTest
    	freopen("Sakura.txt", "r", stdin);
    #endif
    	cin >> n >> m;
    	for(int i = 0; i < m; i++) {
    		int a, b, f, len, tm;
    		cin >> a >> b >> f >> len >> tm;
    		G[a].push_back(edge{b, len, tm});
    		if(!f) G[b].push_back(edge{a, len, tm});	
    	}
    	cin >> _s >> _t;
    	t_dijkstra(), d_dijkstra();
    	if(route[0] == route[1]) printf("Time = %d; ", t[_t]);
    	else{
    		printf("Time = %d: %d", t[_t], _s);
    		for(int i = 1; i < route[0].size(); i++) printf(" => %d", route[0][i]);
    		putchar('
    ');		
    	}
    	printf("Distance = %d: %d",  d[_t], _s);
    	for(int i = 1; i < route[1].size(); i++) printf(" => %d", route[1][i]);
    	return 0;
    }
    
    
  • 相关阅读:
    多线程实际应用踩坑
    SpringBoot远程接口调用-RestTemplate使用
    Python测试Post请求
    Ubuntu基于zsh自定义设置shell主题
    github-share报错无法读取远程仓库
    JVM是如何处理异常的
    springboot之父pom操作
    php 后台json 转 js数组
    tp 外连接查询
    原生关联查询语句
  • 原文地址:https://www.cnblogs.com/yuhan-blog/p/12308627.html
Copyright © 2011-2022 走看看