PAT甲级 - 1003 Emergency (25 分) Dijstra和BF算法

详解BFS,Dijkstra算法,Floyd算法是如何解决最短路径问题的 目录1.BFS算法2.Dijkstra算法3.Floyd算法4.总结G纲是个物流离散中心,经常需要往各个城市运东西,怎么运送距离最近——单源最短路径问题各个城市之间也学要来往,相互之间怎么走距离最近?——每对顶点之间的最短路径如下图,BFS算法是如何实现最短路径问题的呢?设从顶点2开始,第一次搜索的结点为1号结点和6号结点,路径为1,从1号结点和6号结点开始找相邻的接地,5号结点和3号7号为相邻的结点,然后5号结点周围都是已经访问过的,3号结点和7号结点分别搜索搭配4号和8号结点,路径为4 代码 B 阅读详情

As an emergency rescue team leader of a city, you are given a special map of your country. The map shows several scattered cities connected by some roads. Amount of rescue teams in each city and the length of each road between any pair of cities are marked on the map. When there is an emergency call to you from some other city, your job is to lead your men to the place as quickly as possible, and at the mean time, call up as many hands on the way as possible.

Input Specification:

Each input file contains one test case. For each test case, the first line contains 4 positive integers: N (≤500) - the number of cities (and the cities are numbered from 0 to N−1), M - the number of roads, C​1​​ and C​2​​ - the cities that you are currently in and that you must save, respectively. The next line contains N integers, where the i-th integer is the number of rescue teams in the i-th city. Then M lines follow, each describes a road with three integers c​1​​, c​2​​ and L, which are the pair of cities connected by a road and the length of that road, respectively. It is guaranteed that there exists at least one path from C​1​​ to C​2​​.

Output Specification:

For each test case, print in one line two numbers: the number of different shortest paths between C​1​​ and C​2​​, and the maximum amount of rescue teams you can possibly gather. All the numbers in a line must be separated by exactly one space, and there is no extra space allowed at the end of a line.

Sample Input:

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

Sample Output:

2 4

Dijstra图算法的应用,磕磕绊绊的,不过算是自己写完的。

要素

  1. 定义INF,vis[] ,G[][],dis[]
  2. 进入算法,首先处理头结点,然后循环n次{先找到dis最小的节点u,然后以u为中继更新其他未访问节点}
  3. 最短路径的条数:进行累加计数;能找到的队伍数,也是累加计数
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;

const int maxn = 510;
const int INF = 1E9;
int G[maxn][maxn] = { 0 };
int TeamNum[maxn] = { 0 };
int TeamCnt[maxn] = { 0 };
int dis[maxn];
int pathNum[maxn];
bool vis[maxn] = { false };
int N, M, C1, C2;


void Dijstra(int u) {
	dis[u] = 0;
	TeamCnt[u] = TeamNum[u];
	for (int i = 0; i < N; i++) {
		int MIN = INF, u = -1;
		for (int j = 0; j < N; j++) {
			if (vis[j] == false && dis[j] < MIN) { //找到一个未访问的距离最小点作为起点
				MIN = dis[j];
				u = j;
			}
		}
		if (u == -1) return; //if u not update, indicate that not route
		for (int v = 0; v < N; v++) {// update path
			vis[u] = true;
			if (vis[v] == false && G[u][v] != 0) {
				if (dis[u] + G[u][v] < dis[v])
				{
					dis[v] = dis[u] + G[u][v];
					pathNum[v] = pathNum[u];
					TeamCnt[v] = TeamCnt[u] + TeamNum[v];
				}
				else if (dis[u] + G[u][v] == dis[v])
				{
					pathNum[v] += pathNum[u];
					if (TeamCnt[u] + TeamNum[v] > TeamCnt[v])
						TeamCnt[v] = TeamCnt[u] + TeamNum[v];
				}

			}

		}
	}
}

int main() {
	cin >> N >> M >> C1 >> C2;
	fill(dis, dis + maxn, INF);
	fill(pathNum, pathNum + maxn, 1);
	for (int i = 0; i < N; i++)
		cin >> TeamNum[i];
	for (int i = 0; i < M; i++)
	{
		int c1, c2, L;
		cin >> c1 >> c2 >> L;
		G[c1][c2] = L;
		G[c2][c1] = L;
	}
	Dijstra(C1);
	cout << pathNum[C2] << " " << TeamCnt[C2] << endl;
}

Bellman-Ford算法

与Dijstra算法有很大不同,N-1轮,遍历所有边(会重复访问节点)

统计最短路径条数时,由于重复访问节点,要设置前驱set<int> pre[maxn],当相同时,要重新统计前驱和。

num[]数组初始化与Dij相同

Adj邻接表存储,Adj[u][j],j不代表节点地址,只代表Adj中的地址,通过Adj[u][j].v来获取地址

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<vector>
#include<set>
using namespace std;

struct node {
	int v, weight; //代表所连接的点和权值
	node(int _v, int _weight) : v(_v), weight(_weight) {}
};
const int maxn = 510;
const int INF = 1e9;
int dis[maxn];
int w[maxn] = { 0 };
int wCnt[maxn] = { 0 };
int num[maxn] = { 0 };	
int N, M, C1, C2;
vector<node> Adj[maxn];
set<int> pre[maxn];

bool BellmanFord(int source) {
	fill(dis, dis + maxn, INF);
	wCnt[source] = w[source]; //same
	dis[source] = 0; //same
	num[source] = 1;
	for (int i = 0; i < N - 1; i++) {
		for (int u = 0; u < M; u++) {
			for (int j = 0; j < Adj[u].size(); j++)// v is index of type node, not the real node
			{
				int v = Adj[u][j].v;
				int weight = Adj[u][j].weight;
				if (dis[u] + weight < dis[v]) {
					dis[v] = dis[u] + weight;
					wCnt[v] = wCnt[u] + w[v];
					num[v] = num[u];
					pre[v].clear();
					pre[v].insert(u);
				}
				else if (dis[u] + weight == dis[v]) {
					//num[v] += num[u]; 由于重复计数,不能这样使用
					if (wCnt[v] < wCnt[u] + w[v]) {
						wCnt[v] = wCnt[u] + w[v];
					}
					num[v] = 0;
					pre[v].insert(u);
					set<int>::iterator it;
					for (it = pre[v].begin(); it != pre[v].end(); it++) {
						num[v] += num[*it];
					}
				}
			}
		}
	}
	for (int i = 0; i < N - 1; i++) {
		for (int u = 0; u < M; u++) {
			for (int j = 0; j < Adj[u].size(); j++) {
				if (dis[u] + Adj[u][j].weight < dis[Adj[u][j].v])
					return false;
			}
		}
	}
	return true;
}

int main() {
	cin >> N >> M >> C1 >> C2;
	for (int i = 0; i < N; i++)
		cin >> w[i];
	for (int i = 0; i < M; i++)
	{
		int c1, c2, L;
		cin >> c1 >> c2 >> L;
		Adj[c1].push_back(node(c2, L));
		Adj[c2].push_back(node(c1, L));
	}
	if (BellmanFord(C1)) {
		cout << num[C2] << " " << wCnt[C2];
	} // output the number of shortest path
	return 0;
}

 

1003. Emergency (25)-PAT甲级真题(Dijkstra算法) 1003. Emergency (25)As an emergency rescue team leader of a city, you are given a special map of your country. The map shows several scattered cities connected by some roads. Amount of rescue teams in... 阅读详情

相关推荐

ADS 2024 Circuit Envelope 仿真:3步配置调制源,分析5G NR EVM与ACPR

本文详细介绍了ADS 2024 Circuit Envelope仿真技术在5G NR调制源配置与关键指标分析中的应用。通过3步配置调制源,工程师可以高效评估EVM与ACPR等关键指标,特别适用于功放设计中的非线性效应诊断。文章还提供了优化仿真设置和精确提取EVM、ACPR的实用方法,助力5G射频前端设计。

weixin_28559803的博客 385

算法:图的最短路径-BF算法(比普通版迪杰斯特拉快)以牛客网的单元最短路径那道题为例子

牛客网上的单源最短路径问题

weixin_58133735的博客 520

手把手教你用芯驰X9HP驱动MAX96755/MAX96752点亮智能座舱仪表屏(附完整寄存器配置表)

本文详细介绍了如何使用芯驰X9HP驱动MAX96755/MAX96752实现智能座舱仪表屏的完整开发流程,包括硬件架构解析、关键寄存器配置、Linux BSP集成及调试技巧。通过实战指南和完整寄存器配置表,帮助开发者快速掌握驱动开发核心技术,提升智能座舱系统的显示性能与稳定性。

weixin_30879169的博客 526

一份代码四个算法:广度优先BFS、Dijstra、最佳优先BFS、A*

算法不应是背出来的,本文非基础介绍,不会抄定义,全是一些需要思考的内容~~

ReDreamme的博客 766

xHCI驱动学习(1) 核心数据结构

虽然Linux内核拥有C语言构建的身体,但它骨子里散发的是面向对象的气质,这一个个的对象就是struct。面对一个内核模块的时候,首先要找出关键的struct和它们之间的关系,才能摸清代码的骨骼脉络。今天来理清USB xHCI相关的数据结构类型usb_hcd、xhci_hcd、hc_driver和全局变量xhci_pci_driver、xhci_hc_driver、xhci_pci_hc_driver之间的关系。

1万+

【OpenAirInterface知识-3】OAI端到端部署之5G基站部署

在上一篇文章中已经完成了5G核心网的部署,本篇文章将介绍OAI 5G基站的部署过程。

起名字难上难的博客 3423

算法 BF算法

BF算法是字符匹配的一种算法,也称暴力匹配算法算法思想:从主串s1的pos位置出发,与子串s2第一位进行匹配若相等,接着匹配后一位字符若不相等,则返回到s1前一次匹配位置的后一位,接着与s2的起始位进行匹配直到与s2全部匹配成功,则返回在s1中开始完全匹配的下标简单说这个算法的思想就是匹配失败,就重新从上一次匹配位置的下一位开始匹配难理解之处:①i = i - j + 2,这一步是若匹配失败,从上...

夜雨柠檬 1万+

利用VBA宏实现LightTools仿真数据自动化导出至Excel

本文详细介绍了如何利用VBA宏实现LightTools仿真数据自动化导出至Excel的完整流程。通过调用LTAPI接口,工程师可以自动执行仿真、抓取照度与光强等数值数据、捕获并粘贴仿真图像,从而将重复性工作自动化,显著提升光学设计工作的效率和准确性。

weixin_28314575的博客 503

算法笔记——最短路径问题:Dijkstra算法/BF和SPFA/Floyd

//=============算法思路==================== //1:邻接矩阵:一般不超过1000,无向边和有向边的区别 //2:邻接表(用链表),无向边和有向边的区别 //2.1:为了简便,vector(变长数组) //3:Dijkstra算法 //3.1:Di伪代码 //G为图,一般设为全局变量;数据d为源点到各点的最短路径长度,s为起点 //D(G,D[],S) //{ //初始化 //for(循环n次) //{ // u为D[u]中最小的还未被访问的顶点的标号; //

WF19980719的博客 541

Qt入门教程100篇(已完结)

Qt5入门教程,Qt6入门教程。包含了: Qt环境搭建篇、Qt数据类型篇、Qt中STL篇、Qt核心篇、Qt核心对象QObject篇、Qt基础控件篇、Qt对话框篇、Qt高级控件篇、Qt数据模型篇、QSS篇、Qt文件篇 、Qt硬件编程、Qt的一些demo、Qt项目开发篇。......

小鱼酱的博客 15万+

前端build工程的时候 出现 `build.rollupOptions.external 的解决方法

看到这个Bug,理性分析: 遇到 Rollup failed to resolve import “@vue/devtools-api” 错误可能是由于 Pinia 使用了 @vue/devtools-api 模块,而 Vite 的 Rollup 插件无法解析这个模块 ps:但是我前一秒还可以,加了个别代码,突然不行,我是不相信的 = - =

码农研究僧的博客 3056

最短路径之(迪杰斯特拉)Dijkstra算法(及其改进:BF算法,SPFA算法),(弗洛伊德)Floyd算法

最短路径之(迪杰斯特拉)Dijkstra算法(及其改进:BF算法,SPFA算法),(弗洛伊德)Floyd算法: 1.Dijkstra算法不能解决带负权边的图 2.B-F算法做了优化允许图中出现负权边并解决该问题 3.SPFA算法利用队列对B-F算法进一步优化,允许图中可以出现环但是不能解决带环的图(仅能判别出现但是不能解决) 4.Floyd算法能解决负权边但不能解决负环

是小光a~ 3070

华为MetaERP国资委语境下的 DRP(全域数字化资源管理平台/Digitalized Resource-management Platform)与传统 ERP(以 SAP、Oracle 为代表)的

【摘要】国资委推动的DRP(全域数字化资源管理平台)正在重构央国企数智化转型路径,其本质是通过"ERP管交易+DRP管管控"的双层架构实现升维替代。与传统ERP相比,DRP具有三大突破:采用国产分布式数据库实现全级次穿透监管、构建数据中台打破信息孤岛、以实时分析替代事后报表。当前政策明确2026-2030年分阶段建设目标,这将重塑产业格局——倒逼传统ERP厂商转型,为云原生/AI/信创企业创造新机遇。需注意DRP并非简单替代ERP,而是通过治理模式变革实现"交易系统做薄、管控中

金牌架构师 288

鱼额宝 之 error LNK2001: 无法解析的外部符号 之 静态数据成员的定义

C5-1 “鱼额宝” 题目描述 请实现一个“鱼额宝”类,下面已给出代码模板,请根据main函数中对该类的操作,补充类实现部分完成代码。 “鱼额宝”类可以记录账户余额、存钱、取钱、计算利息。该类中有一个私有静态成员变量profitRate存储“鱼额宝”的利率,可以用共有静态成员函数setProfitRate修改利率的值。程序输入为第1天至第n天连续n天的账户操作,每天只能进行一次账户操作,或存...

DedicateToAI的博客 1096

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

学堂在线 c++基础 之 C4-3 一元二次方程求解

题目描述 对于一元二次方程ax^2 + bx + c = 0,解可以分为很多情况。 若该方程有两个不相等实根,首先输出1,换行,然后从小到大输出两个实根,换行; 若该方程有两个相等实根,首先输出2,换行,然后输出这个这个实根,换行; 若该方程有一对共轭复根,输出3,换行; 若该方程有无解,输出4,换行; 若该方程有无穷个解,输出5,换行; 若该方程只有一个根,首先输出6,换行,然后输...

DedicateToAI的博客 1011

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

1101 Quick Sort (25 分)- PAT甲级真题-多种算法及分析

There is a classical process namedpartitionin the famous quick sort algorithm. In this process we typically choose one element as the pivot. Then the elements less than the pivot are moved to its l...

DedicateToAI的博客 980

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

阿里3.25笔试题

自己写的bullshit,第一题5%,第二题0% 第一题原来写的代码: 思路是首先对矩阵所有数求和,然后取平均值,接下来,找到每一列最接近平均值的数,使得起伏最小。 只通过了5%。 #include <iostream> #include <cstdio> #include<vector> #include<algorithm> usi...

DedicateToAI的博客 836

一些比较难懂的递归题目 c++

全排列问题 #include<cstdio> const int maxn = 11; int n, P[maxn], hashTable[maxn] = { false }; void generateP(int index) { if (index == n + 1) { for (int i = 1; i <= n; i++) { printf("%d"...

DedicateToAI的博客 619

2019.12.7PAT冬季考试第二题 - 7-3 Summit (25分)

7-3Summit(25分) Asummit(峰会) is a meeting of heads of state or government. Arranging the rest areas for the summit is not a simple job. The ideal arrangement of one area is to invite those heads so...

DedicateToAI的博客 606

PAT甲级简单题最后冲刺

A1001 Calculatea+band output the sum in standard format -- that is, the digits must be separated into groups of three by commas (unless there are less than four digits). Input Specification: Eac...

DedicateToAI的博客 527

2019.12.7PAT冬季考试第四题 - 7-4 Cartesian Tree (30分)

ACartesian treeis a binary tree constructed from a sequence of distinct numbers. The tree is heap-ordered, and an inorder traversal returns the original sequence. For example, given the sequence { 8...

DedicateToAI的博客 458

学堂在线 C++设计基础 C4-2 反转整数

题目描述 对于输入的一个正整数,输出其反转形式 要求使用c++ class编写程序。可以创建如下class #include &lt;iostream&gt; using namespace std; class Integer{ private: int _num; //getLength()函数获取_num长度 int getLength(){ } publ...

DedicateToAI的博客 427

总结与反思 - 12月7日冬季PAT甲级考试

第一次参加PAT甲级考试,地点在上海大学计算中心。首先要说下这个位置,地图上没有明显的标识,准考证上也没有明确的写,最后是靠自己问路问来的。 上海大学计算中心:首先找到图书馆附近,然后找D楼,D楼的4楼就是计算中心啦。 然后说下环境,机房是比较老的了,不过看上去编译环境还是比较齐全的,python, java, c都有,因为自己之前一直是用的VS2019,这次也打开了vs2010,然后就被坑...

DedicateToAI的博客 388

2019.12.7PAT冬季考试第一题 - 7-1 Good in C (20分)

第一题 7-1Good in C(20分) When your interviewer asks you to write "Hello World" using C, can you do as the following figure shows? Input Specification: Each input file contains one test case. For ...

DedicateToAI的博客 384

PAT - 栈、队列、链表

【Codeup 1918】简单计算器 数据结构node,用来存储操作数和操作符,flag来表示类型 stack操作符栈【遇到相等或者高优先级操作符,弹出】;queue用来存储转换成的后缀表达式;map实现操作符优先级的映射。 使用(getline(cin, str), str!= "0"),来输入若干字符串str,str = "0",终止输入。 使用 string::iterator i...

DedicateToAI的博客 368

2019.12.7PAT冬季考试第二题 - 7-2 Block Reversing (25分)

Given a singly linked listL. Let us consider everyKnodes as ablock(if there are less thanKnodes at the end of the list, the rest of the nodes are still considered as a block). Your job is to re...

DedicateToAI的博客 365
上一篇: PAT - 1076 Forwards on Weibo (30 分) 图的BFS遍历
下一篇: PAT甲级 - 1030 Travel Plan (30 分)
DedicateToAI
博客等级 码龄9年 6粉丝 90原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值