07-图6 旅游规划(25 分)
2017-11-27 21:29
204 查看
其实这题感觉用二维数组方便一些,但为了锻炼和熟悉建表所以选择了链表实现。
07-图6 旅游规划(25 分)
有了一张自驾旅游路线图,你会知道城市间的高速公路长度、以及该公路要收取的过路费。现在需要你写一个程序,帮助前来咨询的游客找一条出发地和目的地之间的最短路径。如果有若干条路径都是最短的,那么需要输出最便宜的一条路径。
输入格式:
输入说明:输入数据的第1行给出4个正整数N、M、S、D,其中N(2≤N≤500)是城市的个数,顺便假设城市的编号为0~(N−1);M是高速公路的条数;S是出发地的城市编号;D是目的地的城市编号。随后的M行中,每行给出一条高速公路的信息,分别是:城市1、城市2、高速公路长度、收费额,中间用空格分开,数字均为整数且不超过500。输入保证解的存在。
输出格式:
在一行里输出路径的长度和收费总额,数字间以空格分隔,输出结尾不能有多余空格。
输入样例:
4 5 0 3 0 1 1 20 1 3 2 30 0 3 4 10 0 2 2 20 2 3 1 20
输出样例:
3 40
#include<iostream> #include<vector> using namespace std; #define MaxNv 500 vector<int> cost(MaxNv,0); vector<int> dist(MaxNv,250001); vector<int> collected(MaxNv,0); struct node{ int v1,v2; int len,cost; }; using ptrtonode=node*; struct enode{ int v; int length; int cost; enode* next; }; using edge=enode*; using firstlist=edge[MaxNv]; struct graph{ int start,end; int Nv; int Ne; firstlist headlist; }; using Graph=graph*; Graph createGraph(){ Graph gra=new graph(); cin>>gra->Nv>>gra->Ne>>gra->start>>gra->end; for(int i=0;i<MaxNv;i++) gra->headlist[i]=NULL; return gra; } void Insertedge(Graph gra,ptrtonode pnode){ edge e=new enode(); e->v=pnode->v2; e->length=pnode->len; e->cost=pnode->cost; e->next=gra->headlist[pnode->v1]; gra->headlist[pnode->v1]=e; e=new enode(); e->v=pnode->v1; e->length=pnode->len; e->cost=pnode->cost; e->next=gra->headlist[pnode->v2]; gra->headlist[pnode->v2]=e; } Graph BuildGraph(){ int v1,v2; Graph gra=createGraph(); ptrtonode pnode=new node(); for(int i=0;i<gra->Ne;i++){ cin>>pnode->v1>>pnode->v2>>pnode->len>>pnode->cost; Insertedge(gra,pnode); } return gra; } int findmin(Graph gra){ int min=3000000; int v=-1; for(int i=0;i<gra->Nv;i++){ if(collected[i]==0&&dist[i]<min) {min=dist[i]; v=i;} } return v; } void Dijikstra(Graph gra,int s){ while(1){ int v=findmin(gra); if(v==-1) break; collected[v]=1; edge ptr=gra->headlist[v]; while(ptr!=NULL&&collected[ptr->v]==0){ if(dist[v]+ptr->length<dist[ptr->v]){ dist[ptr->v]=dist[v]+ptr->length; cost[ptr->v]=cost[v]+ptr->cost;} else if(dist[v]+ptr->length==dist[ptr->v]&&cost[v]+ptr->cost<cost[ptr->v]){ dist[ptr->v]=dist[v]+ptr->length; cost[ptr->v]=cost[v]+ptr->cost; } ptr=ptr->next; } } } void solve(Graph gra){ int s=gra->start; dist[s]=0; edge ptr=gra->headlist[s]; while(ptr!=NULL){ dist[ptr->v]=ptr->length; cost[ptr->v]=ptr->cost; ptr=ptr->next; } Dijikstra(gra,s); cout<<dist[gra->end]<<" "<<cost[gra->end]; } int main(){ Graph gra=BuildGraph(); edge ptr=gra->headlist[0]; solve(gra); return 0; }
相关文章推荐
- 07-图5. 旅游规划(25)
- 07-图5. 旅游规划(25)
- 07-图5. 旅游规划(25)
- 07/11/25 资料整理
- Linux-25-linux基础重要命令02(L005-07)
- 07-图6 旅游规划 (25分)
- 06-2. 旅游规划(25)MOOC
- 07-排序2. Insert or Merge (25)
- 07-图6 旅游规划
- 07-图6 旅游规划 (25分)
- 图的最短路径问题-07-图6 旅游规划
- 07-图6 旅游规划 (25分)
- 3-07. 求前缀表达式的值(25)
- PAT 数据结构 06-图5. 旅游规划(25)Dijkstra最短路径算法
- 07-图6 旅游规划 (25分)
- 07-图6 旅游规划 (25分)
- 07-图6 旅游规划
- 10 07 25 笔记本电脑
- PTA 旅游规划(25 分)
- Android面试题__2013_07_25