HDU 2680 Choose the best route(简单Dijkstra)
http://acm.hdu.edu.cn/showproblem.php?pid=2680
题意:
一个有向图求最短路径.不过起点有很多个,终点只有一个.
分析:
添加一个超级源点,该点到其他普通起点的距离为0.只需要求该超级源到终点的距离即可.
也可以将原图反向,然后求终点到所有起点的最短距离,然后求最小值即可.
AC代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>
#define INF 1e9
using namespace std;
const int maxn=1000+10;
int n,m,end_point;
vector<int> st;//起点集合
struct Edge
{
int from,to,dist;
Edge(int f,int t,int d):from(f),to(t),dist(d){}
};
struct HeapNode
{
int d,u;
HeapNode(int d,int u):d(d),u(u){}
bool operator<(const HeapNode&rhs)const
{
return d>rhs.d;
}
};
struct Dijkstra
{
int n,m;
vector<Edge> edges;
vector<int> G[maxn];
bool done[maxn];
int d[maxn];
void init(int n)
{
this->n=n;
for(int i=0;i<n;i++) G[i].clear();
edges.clear();
}
void AddEdge(int from,int to,int dist)
{
edges.push_back(Edge(from,to,dist));
m = edges.size();
G[from].push_back(m-1);
}
int dijkstra()
{
priority_queue<HeapNode> Q;
for(int i=0;i<n;i++) d[i]=INF;
d[0]=0;
Q.push(HeapNode(d[0],0));
memset(done,0,sizeof(done));
while(!Q.empty())
{
HeapNode x=Q.top(); Q.pop();
int u = x.u;
if(done[u]) continue;
done[u]=true;
for(int i=0;i<G[u].size();i++)
{
Edge &e=edges[G[u][i]];
if(d[e.to] > d[u]+e.dist)
{
d[e.to]=d[u]+e.dist;
Q.push(HeapNode(d[e.to],e.to));
}
}
}
if(d[end_point]==INF) return -1;
return d[end_point];
}
}DJ;
int main()
{
while(scanf("%d%d%d",&n,&m,&end_point)==3)
{
DJ.init(n+1); //n+1是因为我们多加了0号点:超级源
for(int i=0;i<m;i++)
{
int u,v,d;
scanf("%d%d%d",&u,&v,&d);
u,v;
DJ.AddEdge(u,v,d);
}
int w;
scanf("%d",&w);
while(w--)
{
int u;
scanf("%d",&u);
DJ.AddEdge(0,u,0);
}
printf("%d\n",DJ.dijkstra());
}
return 0;
}