题目:http://acm.hdu.edu.cn/showproblem.php?pid=2680
题意:输入第一行:n为有几个点,m为有几条路径,s为终点。接下来m行就是描述路径的。然后输入一个数字w为 有几个起点,然后输入起点。
思路:把0作为起点,然后让0到输入的这几个起点的距离为0,跑一次dijkstra就行了。
代码
#include <iostream>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <stdlib.h>
#include <stdio.h>
#include <queue>
#include <vector>
using namespace std;
const int maxn=1000+5;
const int INF=0x3f3f3f3f;
int n,m,s,p,q,t,w,from,dis[maxn][maxn],vis[maxn];
int len[maxn];
struct HeapNode
{
int d,u;
bool operator < (const HeapNode& rhs) const {
return d>rhs.d;
}
};
void dijkstra(int a)
{
priority_queue<HeapNode>Q;
Q.push((HeapNode){0,a});
while(!Q.empty())
{
HeapNode x=Q.top();
Q.pop();
int u=x.u;
if(vis[u])
continue;
vis[u]=1;
for(int i=0;i<=n;i++)
{
if(len[i]>x.d+dis[u][i]&&vis[i]==0)
{
len[i]=x.d+dis[u][i];
Q.push((HeapNode){len[i],i});
}
}
}
}
int main()
{
while(scanf("%d%d%d",&n,&m,&s)!=EOF)
{
memset(dis,INF,sizeof(dis));
memset(vis,0,sizeof(vis));
for(int i=0;i<=n;i++)
len[i]=INF;
for(int i=0;i<m;i++)
{
scanf("%d%d%d",&p,&q,&t);
if(t<dis[p][q])
{
dis[p][q]=t;
}
}
scanf("%d",&w);
for(int i=0;i<w;i++)
{
scanf("%d",&from);
dis[0][from]=0;
}
dijkstra(0);
if(len[s]<INF)
printf("%d\n",len[s]);
else
printf("-1\n");
}
return 0;
}