最小花费(dijkstra)

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int N=2010,M=1e5+10;
int n,m,start,ed;
double g[N][N];
double dist[N];
bool st[N];
void dijkstra() {
    dist[start]=1;
    st[start]=true;
    for(int i=1;i<=n;i++) dist[i]=g[start][i];
    for(int i=1;i<n;i++){
    	int t=-1;
    	for(int j=1;j<=n;j++){
    		if(!st[j]&&(t==-1||dist[t]<dist[j])) 
    			t=j;
		}
		st[t]=true;
		for(int j=1;j<=n;j++)
			dist[j]=max(dist[j],dist[t]*g[t][j]);
	}
}
int main() {
    cin>>n>>m;
    for(int i=1; i<=m; i++) {
        int a,b;
        double c;
        cin>>a>>b>>c;
        c=(100.0-c)/100.0;
        g[a][b]=g[b][a]=max(g[a][b],c);
    }
    cin>>start>>ed;
    dijkstra();
    printf("%.8lf",100.0/dist[ed]);
    return 0;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用Dijkstra算法求解最短路径及花费的Python代码示例: ```python import heapq def dijkstra(graph, start): # 初始化距离字典和前驱节点字典 distance = {node: float('inf') for node in graph} distance[start] = 0 predecessor = {node: None for node in graph} # 使用堆来进行贪心策略的选择 heap = [(0, start)] while heap: # 弹出堆中的距离最小的节点 (current_distance, current_node) = heapq.heappop(heap) # 如果当前节点已经处理过,则跳过 if current_distance > distance[current_node]: continue # 遍历当前节点的所有邻居节点 for neighbor, weight in graph[current_node].items(): # 计算到邻居节点的距离 new_distance = current_distance + weight # 如果新的距离比之前的距离更小,则更新距离和前驱节点 if new_distance < distance[neighbor]: distance[neighbor] = new_distance predecessor[neighbor] = current_node heapq.heappush(heap, (new_distance, neighbor)) return distance, predecessor # 测试数据 graph = { 'A': {'B': 2, 'C': 1}, 'B': {'A': 2, 'C': 3, 'D': 2}, 'C': {'A': 1, 'B': 3, 'D': 1}, 'D': {'B': 2, 'C': 1, 'E': 4}, 'E': {'D': 4} } # 使用Dijkstra算法求解最短路径及花费 distance, predecessor = dijkstra(graph, 'A') # 输出结果 print("最短距离:", distance) print("前驱节点:", predecessor) ``` 在上述代码中,我们使用堆来进行贪心策略的选择。首先,我们初始化距离字典和前驱节点字典,将起始节点的距离设为0。然后,我们将起始节点压入堆中,并开始遍历堆。每次从堆中弹出距离最小的节点,然后遍历该节点的所有邻居节点。对于每个邻居节点,我们计算到该节点的距离,如果新的距离比之前的距离更小,则更新距离和前驱节点,并将邻居节点压入堆中。最后,当堆为空时,我们就得到了最短路径及花费

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值