次短路
2021/10/3 23:11:48
本文主要是介绍次短路,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
题目链接
poj3255
Roadblocks
Time Limit: 2000MS Memory Limit: 65536K
Description
Bessie has moved to a small farm and sometimes enjoys returning to visit one of her best friends. She does not want to get to her old home too quickly, because she likes the scenery along the way. She has decided to take the second-shortest rather than the shortest path. She knows there must be some second-shortest path.
The countryside consists of R (1 ≤ R ≤ 100,000) bidirectional roads, each linking two of the N (1 ≤ N ≤ 5000) intersections, conveniently numbered 1..N. Bessie starts at intersection 1, and her friend (the destination) is at intersection N.
The second-shortest path may share roads with any of the shortest paths, and it may backtrack i.e., use the same road or intersection more than once. The second-shortest path is the shortest path whose length is longer than the shortest path(s) (i.e., if two or more shortest paths exist, the second-shortest path is the one whose length is longer than those but no longer than any other path).
Input
Line 1: Two space-separated integers: N and R
Lines 2..R+1: Each line contains three space-separated integers: A, B, and D that describe a road that connects intersections A and B and has length D (1 ≤ D ≤ 5000)
Output
Line 1: The length of the second shortest path between node 1 and node N
Sample Input
4 4 1 2 100 2 4 200 2 3 250 3 4 100
Sample Output
450
Hint
Two routes: 1 -> 2 -> 4 (length 100+200=300) and 1 -> 2 -> 3 -> 4 (length 100+250+100=450)
解题思路
跟求次小值类似,即:更新最短路的同时更新次短路,再更新两次次短路:次短路与前一次次短路,当前没有被更新的最短路与次短路~
以spfa
算法为例,其他算法最短路模板同理改动即可~
- 时间复杂度:\(O(kn)\)
代码
#include<queue> #include<cstdio> #include<cstring> using namespace std; const int N=5010; int n,m; vector<pair<int,int> > adj[N]; int d1[N],d2[N]; bool v[N]; void spfa() { memset(v,0,sizeof v); memset(d1,0x3f,sizeof d1); memset(d2,0x3f,sizeof d2); queue<int> q; q.push(1); d1[1]=0; v[1]=true; while(q.size()) { int x=q.front(); q.pop(); v[x]=false; for(int i=0;i<adj[x].size();i++) { int y=adj[x][i].first,w=adj[x][i].second; if(d1[y]>d1[x]+w) { d2[y]=d1[y]; d1[y]=d1[x]+w; if(!v[y]) q.push(y),v[y]=true; } if(d2[y]>d2[x]+w) { d2[y]=d2[x]+w; if(!v[y]) q.push(y),v[y]=true; } if(d1[y]<d1[x]+w&&d2[y]>d1[x]+w) { d2[y]=d1[x]+w; if(!v[y]) q.push(y),v[y]=true; } } } } int main() { scanf("%d%d",&n,&m); while(m--) { int x,y,w; scanf("%d%d%d",&x,&y,&w); adj[x].push_back(make_pair(y,w)); adj[y].push_back(make_pair(x,w)); } spfa(); printf("%d",d2[n]); return 0; }
这篇关于次短路的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-07-04TiDB 资源管控的对撞测试以及最佳实践架构
- 2024-07-03万字长文聊聊Web3的组成架构
- 2024-07-02springboot项目无法注册到nacos-icode9专业技术文章分享
- 2024-06-26结对编程到底难不难?答案在这里
- 2024-06-19《2023版Java工程师》课程升级公告
- 2024-06-15matplotlib作图不显示3D图,怎么办?
- 2024-06-1503-Loki 日志监控
- 2024-06-1504-让LLM理解知识 -Prompt
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现