zoukankan      html  css  js  c++  java
  • PAT

    Nothing to fear


    种一棵树最好的时间是十年前,其次是现在!

    那些你早出晚归付出的刻苦努力,你不想训练,当你觉的太累了但还是要咬牙坚持的时候,那就是在追逐梦想,不要在意终点有什么,要享受路途的过程,或许你不能成就梦想,但一定会有更伟大的事情随之而来。 mamba out~

    2020.7.14


    人一我十,人十我百,追逐青春的梦想,怀着自信的心,永不言弃!

    Travel Plan

    考点: Dijkstra求最短路 + dijkstra记录最短路径 +dfs遍历路径

    题目大意

    求起点到终点的最短路径最短距离和花费,要求首先路径最短,其次花费最少,要输出完整路径

    输出内容:

    分析

    通过dijkstra求出最短路径和修小耗费并通过pre数组记录下来最短路经即可。

    需要注意的点:

    • PAT中初始化的最好初始化为99999999 ,因为PAT不会给除数据范围上限,所以初始化位0x3f / 0x7f在这道题里面最后一个数据点会过不去。望大家注意

    完整代码

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    #include <vector>
    #include <queue>
    
    using namespace std;
    const int N = 1005;
    const int inf = 99999999; // PAT中初始化最好用 99999999 0x3f最后一个测试点过不去
    int e[N][N],cost[N][N];
    int n , m , s , D;
    int dis[N], vis[N] , anscost = inf;
    priority_queue<pair<int,int> > q;
    vector<int> pre[N] , path;
    void dfs(int now , vector<int> tpath)
    {
    	if(now == s)
    	{
    		tpath.push_back(s);int tmpcost = 0;
    		for(int i = tpath.size() - 1;i > 0;i --)
    		{
    			int a = tpath[i] , b = tpath[i - 1];
    			tmpcost += cost[a][b];
    		}
    		if(tmpcost < anscost)
    		{
    			anscost = tmpcost;
    			path = tpath;
    		}
    		return; 
    	}
    	for(int i = 0;i < pre[now].size();i ++)
    	{
    		tpath.push_back(now);
    		dfs(pre[now][i] , tpath);
    		tpath.pop_back();
    	}
    }
    void Dijkstra(int s)
    {
    	memset(dis , 0x3f , sizeof dis);
    	memset(vis, 0 , sizeof vis);
    	dis[s] = 0;q.push({0 , s});
    	while(!q.empty())
    	{
    		int x = q.top().second;q.pop();
    		if(vis[x])continue;
    		vis[x] = 1;
    		for(int i = 0;i < n;i ++)
    		{
    			int y = i , w = e[x][i];
    			if(!vis[y] && w != 0x3f)
    			{
    				if(dis[y] > dis[x] + w)
    				{
    					pre[y].clear();
    					pre[y].push_back(x);
    					dis[y] = dis[x] + w;
    					q.push({-dis[y] , y});
    				}else if(dis[y] == dis[x] + w){
    					pre[y].push_back(x);
    				}
    			}
    		}
    	}
    }	
    int main()
    {
    	memset(e ,0x3f, sizeof e);
    	cin >> n >> m >> s >> D;
    	int a , b , c , d;
    	for(int i = 0;i < m;i ++)
    	{
    		scanf("%d %d %d %d",&a,&b,&c,&d);
    		e[a][b] = e[b][a] = c;
    		cost[a][b] = cost[b][a] = d;
    	}
    	Dijkstra(s);
    	vector<int> t;
    	dfs(D , t);
    	for(int i = path.size() - 1;i >= 0;i --)
    	{
    		printf("%d ", path[i]);
    	}cout << dis[D] << " " << anscost << endl;
    	return 0;
    }
    
  • 相关阅读:
    windows下安装rabbitmq
    selectors
    修改Docker默认镜像和容器的存储位置
    eclipse配置jdk的src.zip源代码步骤
    Zookeeper WINDOWS 安装配置
    zookeeper windows 入门安装和测试
    zookeeper集群搭建(windows环境下)
    ant使用指南详细入门教程
    linux查看系统版本和系统位数
    suse linux 命令
  • 原文地址:https://www.cnblogs.com/wlw-x/p/13301019.html
Copyright © 2011-2022 走看看