初学堆优化的dijkstra算法,正好有道模板题HDU 2066,随便写了一下没想到过了,WA了一次还是上次的毛病,用邻接表构建无向图时没有连两遍。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
const int INF=100000000;
struct edge {int to,cost;};
typedef pair<int,int> P;//first是距离,second是ds里的下标
std::vector<edge> G[1001];
int ds[1001];//最短距离
void dijkstra(int s)
{
priority_queue<P, std::vector<P>, greater<P> > que;//按距离从小到大取出元素的堆
ds[s]=0;
que.push(P(0,s));
while(!que.empty())
{
P p=que.top();//堆顶元素,为还未计算的距离中的最短距离
que.pop();
int v=p.second;
if(ds[v]<p.first)
continue;
for (int i = 0; i < G[v].size(); ++i)
{
edge e=G[v][i];
if (ds[e.to]>ds[v]+e.cost)
{
ds[e.to]=ds[v]+e.cost;
que.push(P(ds[e.to],e.to));
}
}
}
}
int main(int argc, char const *argv[])
{
int t,s,d;
while(scanf("%d%d%d",&t,&s,&d)!=EOF)
{
fill(ds,ds+1001,INF);
ds[0]=0;
for (int i = 0; i < 1001; ++i)
G[i].clear();
while(t--)
{
int a,b,time;
scanf("%d%d%d",&a,&b,&time);
edge tem;
tem.to=b;
tem.cost=time;
G[a].push_back(tem);
tem.to=a;
G[b].push_back(tem);//无向图注意连两遍
}
while(s--)
{
int dir;
scanf("%d",&dir);
edge tem;
tem.to=dir;
tem.cost=0;
G[0].push_back(tem);
}
dijkstra(0);
int ans=INF;
while(d--)
{
int des;
scanf("%d",&des);
if(ds[des]<ans)
ans=ds[des];
}
printf("%d\n",ans);
}
return 0;
}