多源点最短路径
2016-04-29 20:48
288 查看
给出s个起点,给出t个终点,求出所有起点到终点的最短路中的最短的一个.
构建一个超级源点,与每一个起点相连,权值为0;构建一个超级终点,与每一个终点相连,权值为0。然后求超级源点到超级终点的最短路径。
构建一个超级源点,与每一个起点相连,权值为0;构建一个超级终点,与每一个终点相连,权值为0。然后求超级源点到超级终点的最短路径。
#include<iostream> #include<queue> using namespace std; int first[1010], dist[1010]; int point[202010], weight[202010], next[202010]; int q[50000]; bool f[1010]; int n,m,s,t,tot; void addEdge(int x, int y, int w) //边集数组保存图 { tot++; point[tot] = y; next[tot] = first[x]; first[x] = tot; weight[tot] = w; tot++; point[tot] = x; next[tot] = first[y]; first[y] = tot; weight[tot] = w; } void spfa_slf() { int h = 0; int t = 0; q[t] = 0; f[0] = true; while (h <= t) { int now = q[h]; h++; f[now] = false; int k = first[now]; while (k != 0) { int New = point[k]; if (dist[now] + weight[k] < dist[New]) { dist[New] = dist[now] + weight[k]; if (!f[New]) { t++; q[t] = New; f[New] = true; } } k = next[k]; } } } int main() { while (cin>>n>>m>>s>>t && n && m && s && t) { tot = 0; for (int i=1; i<=m; i++) { int x, y, w; cin>>x>>y>>w; addEdge(x,y,w); } for (int i=1; i<=s; i++) //构建超级源点 { int x; cin>>x; addEdge(0,x,0); } for (int i=1; i<=t; i++) //构建超级终点 { int x; cin>>x; addEdge(x,n+1,0); } for (int i=0; i<=n+1; i++) { dist[i] = (1<<30); f[i] = false; } dist[0] = 0; spfa_slf(); //spfa求最短路径 if (dist[n+1] < (1<<30)) cout<<dist[n+1]<<endl; else cout<<"What a pity!"<<endl; for (int i=0; i<=n+1; i++) first[i] = dist[i] = f[i] = 0; for (int i=0; i<=tot; i++) point[i] = next[i] = weight[i] = 0; } return 0; }
相关文章推荐
- iOS 硬件 定位 - 地理编码和反地理编码
- 【LeetCode】LeetCode——第15题:3Sum
- Git建立分支
- BZOJ4071: [Apio2015]巴邻旁之桥
- Centos7安装mysql-5.7.11
- 无向图的最短路径算法JAVA实现(转)
- iOS 硬件 定位 - 指南针
- Spring之Bean(二)
- 三级排序
- iOS 硬件 定位 - 详解 数据的处理
- linux先进程通信 管道方式和消息队列
- 最短路径算法-Dijkstra算法的应用之单词转换(词梯问题)(转)
- PHP经典算法过桥。
- 输入框和div拖动
- Linux ssh密钥自动登录 专题
- iOS 硬件
- iOS 硬件 定位 - 前台
- 如何设置文本文件的默认保存编码为UTF-8
- 4月末开坑,4.29-?
- JAVA EE的学习路线