PAT1003Emergency

本文深入讲解了Dijkstra算法的应用,特别是在寻找带权重的最短路径问题中如何处理多个节点之间的救援人数最大化的复杂情况。通过定义结构体和使用动态规划的思想,文章详细解释了算法的实现过程,并给出了具体的代码示例。
摘要由CSDN通过智能技术生成
#include<stdio.h>
#include<stdlib.h>
#include<vector>
#include<queue>
#include<algorithm>
#include<unordered_map>
#include<iostream>
#include<string>
#define INFINITY 9999999
using namespace std;
int N, M, C1, C2;
int rescue[500];
struct Node {
	int Location;
	int distance;
};
int MaxRescueNum[500];
vector<vector<Node>>G(500);
int Distance[500];
int shortestPath[500];
bool visited[500];
int FindMinDistance();
void Dijkstra();
int main()
{
	scanf("%d %d %d %d",&N,&M,&C1,&C2);
	for (int i = 0; i < N; i++)
	{
		scanf("%d", rescue + i);
	}
	for (int i = 0; i < M; i++)
	{
		int node1, node2, distance;
		scanf("%d %d %d", &node1, &node2, &distance);
		G[node1].push_back({ node2,distance });
		G[node2].push_back({ node1,distance });
	}
	Dijkstra();



}
void Dijkstra()
{
	for (int i = 0; i < N; i++)
	{
		Distance[i] = INFINITY;
	}
	shortestPath[C1] = 1;
	Distance[C1] = 0;
	visited[C1] = 1;
	MaxRescueNum[C1] = rescue[C1];
	for (int i = 0; i < G[C1].size(); i++)
	{
		Distance[G[C1][i].Location] = G[C1][i].distance;
		shortestPath[G[C1][i].Location] = 1;
		MaxRescueNum[G[C1][i].Location] = MaxRescueNum[C1] + rescue[G[C1][i].Location];
	}
	while (1)
	{
		int Location = FindMinDistance();
		visited[Location] = true;
		if (visited[C2]==true)
		{
			break;
		}
		else
		{
			for (int i = 0; i < G[Location].size(); i++)
			{
				if (Distance[G[Location][i].Location] > Distance[Location] + G[Location][i].distance)
				{
					Distance[G[Location][i].Location] = Distance[Location] + G[Location][i].distance;
					MaxRescueNum[G[Location][i].Location] = MaxRescueNum[Location] + rescue[G[Location][i].Location];
					shortestPath[G[Location][i].Location] = shortestPath[Location];
				}
				else if (Distance[G[Location][i].Location] == Distance[Location] + G[Location][i].distance)//距离相等
				{
					shortestPath[G[Location][i].Location] += shortestPath[Location];
					MaxRescueNum[G[Location][i].Location] = max(MaxRescueNum[G[Location][i].Location], MaxRescueNum[Location]+rescue[G[Location][i].Location]);
				}
			}
		}
	}
	printf("%d %d", shortestPath[C2], MaxRescueNum[C2]);

}
int FindMinDistance()
{
	int MinDistance = INFINITY;
	int Location=-1;
	for (int i = 0; i < N; i++)
	{
		if (visited[i] == false)
		{
			if (MinDistance > Distance[i])
			{
				Location = i;
				MinDistance = Distance[i];
			}
		}
	}
	return Location;
}```

测试点2错误原因:找到等长的路应该是

```cpp
shortestPath[G[Location][i].Location] += shortestPath[Location];

而不是

shortestPath[G[Location][i].Location] += shortestPath[Location];

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值