您的位置:首页 > 其它

多源点最短路径

2016-04-29 20:48 288 查看
给出s个起点,给出t个终点,求出所有起点到终点的最短路中的最短的一个.

构建一个超级源点,与每一个起点相连,权值为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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: