1013 Problem M

题意:乘公交车的价格根据公交站距离有所不同,对于给定的起点和终点,求得最小的花费费用。

思路:最短路径问题,使用dijkstra算法,根据题目适当变形即可。

感想:在这里需要注意,题目中数据比较大,在定义最大值时,值必须要足够大才可以。

#include

#include

using namespace std;

const long long inf=0xffffffffffffff;

long long dist[105],node[105],vis[105];

long long l[5],c[5],n;

long long cmp(long long a)

{

   return a>0?a:-a;

}

long long cost(long long dis)

{

   if (dis>=0&&dis<=l[1]) return c[1];

   if (dis>l[1]&&dis<=l[2]) return c[2];

   if (dis>l[2]&&dis<=l[3]) return c[3];

   if (dis>l[3]&&dis<=l[4]) return c[4];

}

 

void Dijkstra(long long s,long long e)

{

   for(int i=1; i<=n; i++)

       node[i]=inf,vis[i]=0;

   long long tm=s;

   node[tm]=0;

   vis[tm]=1;

   for(int k=1; k<=n; k++)

    {

       long long mmin=inf;

       for (int i=1; i<=n; i++)

           if(!vis[i]&&mmin>node[i])

           {

                mmin=node[i];

                tm=i;

           }

       if(tm==e)

       {

           printf("The minimum cost between station %I64d and station %I64d is%I64d.\n",s,e,node[e]);

           return ;

       }

       vis[tm]=1;

       for(int i=1; i<=n; i++)

           if(cmp(dist[i]-dist[tm])<=l[4]&&!vis[i]&&node[i]>node[tm]+cost(cmp(dist[i]-dist[tm])))

           {

                node[i]=node[tm]+cost(cmp(dist[i]-dist[tm]));

           }

    }

   printf ("Station %I64d and station %I64d are notattainable.\n",s,e);

}

 

int main ()

{

   int t,k=1;

   cin>>t;

   while (t--)

    {

       cin>>l[1]>>l[2]>>l[3]>>l[4]>>c[1]>>c[2]>>c[3]>>c[4];

       int m;

       cin>>n>>m;

       for(int i=1; i<=n; i++)

           cin>>dist[i];

       printf ("Case %d:\n",k++);

       while (m--)

       {

           int a,b;

           cin>>a>>b;

           Dijkstra(a,b);

       }

    }

   return 0;

}

你可能感兴趣的:(图)