#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
#define Maxn 1010
#define Maxm 1010*1010
#define INT_MAX 1<<30
int used[Maxn],head[Maxn],outqueue[Maxn],queue[Maxn],low[Maxn],temp=-999999999,len = 0;
struct EdgeNode
{
int to,w,next;
}edge[Maxm];
bool SPFA(int start)
{
int i,iq;
for(i = 0;i <= temp;i++)
{
low[i] = INT_MAX;
}
memset(used,0,sizeof(used));
memset(outqueue,0,sizeof(outqueue));
iq = 0;
queue[iq++] = start;
used[start] = 1;
low[start] = 0;
i = 0;
while(i!=iq)
{
int top = queue[i];
used[top] = 0;
outqueue[top]++;
if(outqueue[top] > temp) return false;
for(int k = head[top];k!=-1;k = edge[k].next)
{
if(low[edge[k].to] > low[top] + edge[k].w)
{
low[edge[k].to] = low[top] + edge[k].w;
}
if(!used[edge[k].to])
{
used[edge[k].to] = 1;
queue[iq++] = edge[k].to;
len++;
}
}
i++;
}
return true;
}
int main()
{
int T,S,D;
while(~scanf("%d%d%d",&T,&S,&D))
{
memset(head,-1,sizeof(head));
int i,j,p=0;
int a,b,w;
int x,y;
for(i = 0;i < T;i++)
{
scanf("%d%d%d",&a,&b,&w);
edge[p].to = b;
edge[p].w = w;
edge[p].next = head[a];
head[a] = p++;
edge[p].to = a;
edge[p].w = w;
edge[p].next = head[b];
head[b] = p++;
if(a > temp) temp = a;
if(b > temp) temp = b;
}
temp++;
for(i = 0;i < S;i++)
{
scanf("%d",&x);
edge[p].to = x;
edge[p].w = 0;
edge[p].next = head[0];
head[0] = p++;
edge[p].to = 0;
edge[p].w = 0;
edge[p].next = head[x];
head[x] = p++;
}
for(i = 0;i < D;i++)
{
scanf("%d",&y);
edge[p].to = y;
edge[p].w = 0;
edge[p].next = head[temp];
head[temp] = p++;
edge[p].to = temp;
edge[p].w = 0;
edge[p].next = head[y];
head[y] = p++;
}
// for(i = 0;i <= temp;i++)
// {
// for(j = head[i];j != -1;j = edge[j].next)
// {
// cout<<i<<" "<<edge[j].to<<" "<<edge[j].w<<endl;
// }
// }
SPFA(0);
printf("%d\n",low[temp]);
}
return 0;
}
建图的时候一定要建双向的因为有used这个数组进行已遍历的判断所以不用担心
HDU 2066 SPFA实现0ms
最新推荐文章于 2024-11-07 22:16:19 发布
本文深入探讨了SPFA(Shortest Path Faster Algorithm)算法的实现细节及其在图论问题中的应用。通过具体实例展示了如何使用SPFA算法解决带权有向图中的最短路径问题,并介绍了关键的数据结构和循环检测技巧。
摘要由CSDN通过智能技术生成