对dijkstra的浅见(引例 poj 2457)

本文介绍了非负权值单源最短路径问题中的Dijkstra算法,核心思想是路径长度递增的贪心策略。算法通过不断更新点到源点的最短距离并选择最小距离点作为当前点,逐步构造最短路径。以POJ 2457题目为例,展示了算法的应用和解题过程。
摘要由CSDN通过智能技术生成

非负权值的单源最短路之 dijkstra

Tanky Woo之dijkstra:  http://www.wutianqi.com/?p=1890


dijkstra-------我认为这个算法的核心思想是:最短路径长度递增。其实就是一个贪心算法。

怎么理解呢?

      最短路的最优子结构:假如有一条最短路径已经存在了,那么其中任意两点的路径都将是最短的,否则假设是不成立了。


算法实现过程:

  1.      已当前点 pos 更新,dis[ i ]的值(即 点 i 到源点的距离)
  2.      找出dis[ i ] 最小的 i 点,作为当前 pos 点,并且加入集合 S ,
  3.      重复 1 ,2步骤,N次,因为每次都会找出一个点,一共只有N个点;


以poj 2457为例:


                                                                                                Part Acquisition

Description

The cows have been sent on a mission through space to acquire a new milking machine for their barn. They are flying through a cluster of stars containing N (1 <= N <= 50,000) planets, each with a trading post.

The cows have determined which of K (1 <= K <= 1,000) types of objects (numbered 1..K) each planet in the cluster desires, and which products they have to trade. No planet has developed currency, so they work under the barter system: all trades consist of each party trading exactly one object (presumably of different types).

The cows start from Earth with a canister of high quality hay (item 1), and they desire a new milking machine (item K). Help them find the best way to make a series of trades at the planets in the cluster to get item K. If this task is impossible, output -1.

Input

* Line 1: Two space-separated integers, N and K.

* Lines 2..N+1: Line i+1 contains two space-separated integers, a_i and b_i respectively, that are planet i's trading trading products. The planet will give item b_i in order to receive item a_i.

Output

* Line 1: One more than the minimum number of trades to get the milking machine which is item K (or -1 if the cows cannot obtain item K).

* Lines 2..T+1: The ordered list of the objects that the cows possess in the sequence of trades.

Sample Input

6 5
1 3
3 2
2 3
3 1
2 5
5 4

Sample Output

4
1
3
2
5

Hint

OUTPUT DETAILS:

The cows possess 4 objects in total: first they trade object 1 for object 3, then object 3 for object 2, then object 2 for object 5.



题意:物品交换:n个交换方式,k是目标物品,用物品1 换k,求最少交换的次数。

思路:建图 map[u][v]=1,权值为 1,表示一次交换,即每条路都是一种交换方式,由题是单向图。


代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define INF 0x3f3f3f3f
#define maxn 1000+10
using namespace std;
int map[maxn][maxn];
int dis[maxn];
int pre[maxn];
int kind;

void dijkstra(int s)
{
    int vis[maxn],minn,pos;
    memset(vis,0,sizeof vis);
    for(int i=0;i<kind+1;i++)
        dis[i]=INF;
    dis[s]=0;
    for(int i=0;i<kind;i++)
    {
        minn=INF;
        for(int j=1;j<=kind;j++)
            if(!vis[j]&&minn>dis[j])
            {
                minn=dis[j];
                pos=j;
            }
        vis[pos]=1;
        for(int j=1;j<=kind;j++)
            if(!vis[j]&&dis[j]>dis[pos]+map[pos][j])
            {
                pre[j]=pos;
                dis[j]=dis[pos]+map[pos][j];                   //每更新一遍dis ,刷新一遍 pre
            }

    }
}

void print_path(int aim)  //路径输出函数
{

    int n=dis[aim];          // dis是多少,就交换了多少次,有多少个前驱。
    int path[maxn];          //倒着记录路径
    int step=0,temp;
    path[++step]=aim;
    temp=aim;
    printf("%d\n",n+1);
    for(int i=0;i<n;i++)
    {
        temp=pre[temp];
        path[++step]=temp;
    }
 
    for(int i=step;i>=1;i--)  //倒着输出
        printf("%d\n",path[i]);
}



int main()
{
    int n,k;
    while(scanf("%d%d",&n,&k)!=EOF)
    {
        int u,v;
        kind=-1;
        for(int i=0;i<maxn;i++)
            for(int j=0;j<maxn;j++)
                map[i][j]=INF;
        for(int i=0;i<n;i++)
        {
            scanf("%d%d",&u,&v);
            map[u][v]=1;
            if(kind<max(u,v))
                kind=max(u,v);
        }
        dijkstra(1);
        if(dis[k]<INF)
            print_path(k);
        else
            printf("-1\n");

    }

    return 0;
}




当然了,这一题还涉及了一个对最短路径的输出问题。
如何输出呢?

设置一个pre [ i ]=pos 数组,记录点 i 的前驱点 pos

为何要设置前驱点呢?
    因为dijkstra更新dis【】的时候是根据 pos点更新的,所以每更新一次,就要刷新一遍pre[ ]数组;
    即:仅仅只有松弛操作,会对点 v 的前驱点进行改变,所以每进行一遍松弛操作,就要更新前驱结点。


当然了,你可以利用递归函数输出path:

void print(int v)
{


    int temp;
    //printf("%d\n",dis[v]+1);
    if(v==1)
        printf("1\n");
    else
    {
        temp=pre[v];
        print(temp);
        printf("%d\n",v);
    }
}






  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 用Python实现Dijkstra算法的堆优化需要使用堆数据结构来存储节点,然后使用优先队列来保存最小距离的节点,以便从中每次选取最小距离的节点。这样可以提高搜索算法的效率,从而实现Dijkstra算法的堆优化。 ### 回答2: Dijkstra算法是一种用于求解最短路径问题的经典算法,但其在处理大规模图时效率较低。为了提高其效率,可以通过堆优化的方式来实现。下面是用Python对Dijkstra算法进行堆优化的一种方法: 1. 首先,导入所需的库,包括heapq(堆队列算法模块)和sys(系统相关模块): ```python import heapq import sys ``` 2. 创建一个图的类,包括初始化、添加边和运行Dijkstra算法的方法: ```python class Graph: def __init__(self, vertex_num): self.vertex_num = vertex_num self.edges = [[] for _ in range(vertex_num)] def add_edge(self, u, v, weight): self.edges[u].append((v, weight)) def dijkstra(self, start): distances = [sys.maxsize] * self.vertex_num # 初始距离设置为无穷大 distances[start] = 0 heap = [(0, start)] # 用堆来保存节点和其距离的元组 while heap: curr_distance, curr_vertex = heapq.heappop(heap) # 弹出堆顶(距离最短的节点) if curr_distance > distances[curr_vertex]: # 如果该节点已被处理过,则跳过 continue for neighbor, edge_weight in self.edges[curr_vertex]: # 遍历当前节点的邻居节点 distance = curr_distance + edge_weight if distance < distances[neighbor]: # 更新邻居节点的最短距离 distances[neighbor] = distance heapq.heappush(heap, (distance, neighbor)) # 将邻居节点及其更新后的距离压入堆 return distances ``` 3. 创建一个Graph对象,并调用其方法添加边和运行Dijkstra算法: ```python if __name__ == "__main__": g = Graph(6) g.add_edge(0, 1, 5) g.add_edge(0, 2, 2) g.add_edge(1, 3, 4) g.add_edge(1, 4, 2) g.add_edge(2, 1, 1) g.add_edge(2, 3, 4) g.add_edge(3, 4, 2) g.add_edge(3, 5, 5) g.add_edge(4, 5, 3) distances = g.dijkstra(0) print(distances) ``` 上述代码实现了对Dijkstra算法的堆优化。通过使用堆来保存节点和其距离的元组,可以在每次选择最短距离的节点时提高效率。此外,在处理大规模图时,Dijkstra算法的堆优化版本相对于原始版本具有更高的效率。 ### 回答3: Dijkstra算法是一种用于解决最短路径问题的经典算法,它可以在带权重的有向图中找到起点到其他所有顶点的最短路径。 要实现Dijkstra算法的堆优化,首先需要引入堆数据结构。Python中可以使用heapq模块来实现堆。 接下来,我们需要定义一个最小堆,并初始化一个距离数组和堆数组。距离数组用于存储每个顶点到起点的距离,堆数组用于存储顶点的索引。 首先,将起点的距离设置为0,并将其添加到堆中。然后,对于堆不为空的情况下,重复以下步骤: 1. 弹出堆中最小距离的顶点作为当前顶点。 2. 遍历当前顶点的所有邻接顶点,计算通过当前顶点到达这些邻接顶点的距离。 3. 如果新的距离小于邻接顶点的当前距离,则更新距离数组,并将邻接顶点添加到堆中。 最后,距离数组中存储的即为起点到其他所有顶点的最短路径长度。 下面是使用Python实现Dijkstra算法的堆优化的示例代码: ```python import heapq def dijkstra_heap(graph, start): n = len(graph) distance = [float('inf')] * n distance[start] = 0 heap = [] heapq.heappush(heap, (0, start)) while heap: dist, node = heapq.heappop(heap) if dist > distance[node]: continue for neighbor, weight in graph[node]: new_dist = dist + weight if new_dist < distance[neighbor]: distance[neighbor] = new_dist heapq.heappush(heap, (new_dist, neighbor)) return distance ``` 在这个例子中,`graph`是一个邻接表形式的图表示,`start`是起点的索引。函数`dijkstra_heap`返回一个包含起点到其他顶点的最短路径距离的数组。 这就是如何使用Python对Dijkstra算法进行堆优化的方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值