F - Choose the best route HDU - 2680 ——链式前向星+dijkstra

One day , Kiki wants to visit one of her friends. As she is liable to carsickness , she wants to arrive at her friend’s home as soon as possible . Now give you a map of the city’s traffic route, and the stations which are near Kiki’s home so that she can take. You may suppose Kiki can change the bus at any station. Please find out the least time Kiki needs to spend. To make it easy, if the city have n bus stations ,the stations will been expressed as an integer 1,2,3…n.
Input
There are several test cases.
Each case begins with three integers n, m and s,(n<1000,m<20000,1=

#include<iostream>
#include<cstring>
#include<stdio.h>
#include<queue>
using namespace std;
int head[1005],vis[1005],dist[1005],cnt,n,m,s;
struct e
{
     int to;
     int next;
     int val;
}edge[400005];
struct node 
{
     int id;
     int val;
     node(int id,int val):id(id),val(val){}
     bool operator < (const node& a)const
     {
          return val>a.val;
     }
};
void init(int x,int y,int z)
{
     edge[++cnt].to=x;
     edge[cnt].next=head[y];
     edge[cnt].val=z;
     head[y]=cnt;
}
priority_queue<node>Q;
void dijkstra(int x)
{
     dist[x]=0;
     Q.push(node(x,0));
     while(!Q.empty())
     {
          int u=Q.top().id;
          Q.pop();
          vis[u]=1;
          for(int i=head[u];~i;i=edge[i].next)
          {
               int v=edge[i].to;
               if(vis[v])
                   continue;
               if(dist[v]-edge[i].val>dist[u])
               {
                    dist[v]=dist[u]+edge[i].val;
                    Q.push(node(v,dist[v]));
               }
          }
     }
}
int main()
{
     while(scanf("%d%d%d",&n,&m,&s)!=EOF)
     {
          int sum=1e9;
          int cnt=0;
          memset(head,-1,sizeof(head));
          memset(dist,125,sizeof(dist));
          memset(vis,0,sizeof(vis));
          for(int i=1;i<=m;i++)
          {
               int x,y,z;
               scanf("%d%d%d",&x,&y,&z);
               init(x,y,z);
          }
          dijkstra(s);
          int t;
          scanf("%d",&t);
          for(int i=1;i<=t;i++)
          {
               int a;
               scanf("%d",&a);
               if(dist[a]<sum)
                   sum=dist[a];
          }
          if(sum>=1e9)
              printf("-1\n");
          else
              printf("%d\n",sum);
     }
 return 0;
}

猜你喜欢

转载自blog.csdn.net/tianyizhicheng/article/details/82011357