• HDU 1385 Minimum Transport Cost( Floyd + 记录路径 )



    **链接:****传送门 **

    题意:有 n 个城市,从城市 i 到城市 j 需要话费 Aij ,当穿越城市 i 的时候还需要话费额外的 Bi ( 起点终点两个城市不算穿越 ),给出 n × n 大小的城市关系图,-1 代表两个城市无法连通,询问若干次,求出每次询问的两个城市间的最少花费以及打印出路线图

    思路:经典最短路打印路径问题,直接使用一个二维数组 path[i][j] 记录由点 i 到点 j 最短路的最后后继点,这道题关键是当松弛操作相等时,i 到 j 的最短距离是可以由 k 进行跳转的,这时候需要判断这两条路径哪个字典序更小,也就是比较这两条路的直接后继节点的大小( path[i][j] ? path[i][k] ),并更新最小字典序路径。


    /*************************************************************************
        > File Name: hdu1385t2.cpp
        > Author:    WArobot 
        > Blog:      http://www.cnblogs.com/WArobot/ 
        > Created Time: 2017年06月14日 星期三 16时56分08秒
     ************************************************************************/
    
    #include<bits/stdc++.h>
    using namespace std;
    
    const int MAX_N = 2010;
    const int INF = 1e9;
    int c[MAX_N] , dis[MAX_N][MAX_N] , path[MAX_N][MAX_N];	// path[i][j] 代表i到j这条最短路中的直接后继编号
    int n , st , ed;
    
    void input(){
    	for(int i = 0 ; i < n ; i++){
    		for(int j = 0 ; j < n ; j++){
    			scanf("%d",&dis[i][j]);
    			if( dis[i][j] == -1 )	dis[i][j] = INF;
    		}
    	}
    	for(int i = 0 ; i < n ; i++)	scanf("%d",&c[i]);
    }
    
    void floyd(){
    	for(int i = 0 ; i < n ; i++)
    		for(int j = 0 ; j < n ; j++)	path[i][j] = j;
    	for(int k = 0 ; k < n ; k++){
    		for(int i = 0 ; i < n ; i++){
    			for(int j = 0 ; j < n ; j++){
    				if( dis[i][j] > dis[i][k] + dis[k][j] + c[k] ){
    					dis[i][j] = dis[i][k] + dis[k][j] + c[k];
    					path[i][j] = path[i][k];
    				}
    				else if( dis[i][j] == dis[i][k] + dis[k][j] + c[k] ){
    					if( path[i][j] > path[i][k] ){
    						path[i][j] = path[i][k];
    					}
    				}
    			}
    		}
    	}
    }
    
    vector<int> get_path(int st,int ed){
    	int t = st;
    	vector<int> ret;
    	for( ; t != ed ; t = path[t][ed] )	ret.push_back(t);
    	ret.push_back(ed);
    	return ret;
    }
    int main(){
    	while(~scanf("%d",&n) && n){
    		input();
    		floyd();
    		bool first = true;
    		while(true){
    			if( !first )	puts("");
    			first = false;
    			scanf("%d%d",&st,&ed);
    			if( st == -1 && ed == -1 )	break;
    			if( st == ed ){
    				printf("From %d to %d :
    Path: ",st,ed);
    				printf("%d
    ",st);
    				printf("Total cost : 0
    ");
    			}else {
    				printf("From %d to %d :
    Path: ",st--,ed--);
    				vector<int> ans = get_path(st,ed);
    				for(int i = 0 ; i < ans.size()-1 ; i++)		printf("%d-->",ans[i]+1);
    				printf("%d
    Total cost : %d
    ",ans[ans.size()-1]+1 , dis[st][ed]);
    			}
    		}
    	}
    	return 0;
    }
  • 相关阅读:
    LeetCode_222.完全二叉树的节点个数
    LeetCode_219.存在重复元素 II
    LeetCode_217.存在重复元素
    LeetCode_215.数组中的第K个最大元素
    LeetCode_21.合并两个有序链表
    LeetCode_206.反转链表
    LeetCode_205.同构字符串
    LeetCode_202.快乐数
    LeetCode_20.有效的括号
    LeetCode_2.两数相加
  • 原文地址:https://www.cnblogs.com/WArobot/p/7010762.html
Copyright © 2020-2023  润新知