紧急救援(Dijkstra算法)

来源:互联网 发布:mac配置adb环境变量 编辑:程序博客网 时间:2024/05/08 06:08

紧急救援

作为一个城市的应急救援队伍的负责人,你有一张特殊的全国地图。在地图上显示有多个分散的城市和一些连接城市的快速道路。每个城市的救援队数量和每一条连接两个城市的快速道路长度都标在地图上。当其他城市有紧急求助电话给你的时候,你的任务是带领你的救援队尽快赶往事发地,同时,一路上召集尽可能多的救援队。

输入格式:

输入第一行给出4个正整数N、M、S、D,其中N(2<=N<=500)是城市的个数,顺便假设城市的编号为0~(N-1);M是快速道路的条数;S是出发地的城市编号;D是目的地的城市编号。第二行给出N个正整数,其中第i个数是第i个城市的救援队的数目,数字间以空格分隔。随后的M行中,每行给出一条快速道路的信息,分别是:城市1、城市2、快速道路的长度,中间用空格分开,数字均为整数且不超过500。输入保证救援可行且最优解唯一。

输出格式:

第一行输出不同的最短路径的条数和能够召集的最多的救援队数量。第二行输出从S到D的路径中经过的城市编号。数字间以空格分隔,输出首尾不能有多余空格。

输入样例:
4 5 0 320 30 40 100 1 11 3 20 3 30 2 22 3 2
输出样例:
2 600 1 3
#include <cstdio>#include <queue>#include <cstring>#include <vector>#include <iostream>#define MAXN 0X7FFFFFFFusing namespace std;struct node{int to;int weight;int next;}edge[250000];struct node1{int to;int dis;int w;node1(int a,int b,int c):to(a),dis(b),w(c){}bool operator <(node1 b)const{if(this->dis!=b.dis)return this->dis>b.dis;elsereturn this->w<b.w;}};int cnt,head[600];int n,m,s,d,save[600];//save为给出的每个城市的救援队数量void Add(int x,int y,int w){cnt++;edge[cnt].to=y;edge[cnt].weight=w;edge[cnt].next=head[x];head[x]=cnt;}void Dijkstra(int start,int end){int distance[600],pre[600],count[600],peo[600],book[600];//count为道路数量,pre用于打印路径,peo为已经召集的救援队数量priority_queue<node1> q;for(int i=0;i<n;i++){distance[i]=MAXN;}memset(book,0,sizeof(book));memset(pre,-1,sizeof(pre));memset(count,0,sizeof(count));distance[start]=0;count[start]=1;peo[start]=save[start];q.push(node1(start,0,peo[start]));while(!q.empty()){node1 t=q.top();q.pop();if(book[t.to]){continue;}book[t.to]=1;for(int i=head[t.to];i;i=edge[i].next){if(distance[edge[i].to]>distance[t.to]+edge[i].weight){distance[edge[i].to]=distance[t.to]+edge[i].weight;pre[edge[i].to]=t.to;peo[edge[i].to]=peo[t.to]+save[edge[i].to];count[edge[i].to]=count[t.to];q.push(node1(edge[i].to,distance[edge[i].to],peo[edge[i].to]));}else if(distance[edge[i].to]==distance[t.to]+edge[i].weight){count[edge[i].to]+=count[t.to];if(peo[edge[i].to]<peo[t.to]+save[edge[i].to]){pre[edge[i].to]=t.to;peo[edge[i].to]=peo[t.to]+save[edge[i].to];q.push(node1(edge[i].to,distance[edge[i].to],peo[edge[i].to]));}}}}printf("%d %d\n",count[end],peo[end]);if(start==end){printf("%d %d\n",start,end);return;}int now=end;vector<int> v;v.clear();do{v.push_back(now);now=pre[now];}while(now!=-1);for(int i=v.size()-1;i>=0;i--){printf("%d%c",v[i],i==0?'\n':' ');}return;}int main(){int x,y,z;cin>>n>>m>>s>>d;for(int i=0;i<n;i++){cin>>x;save[i]=x;}for(int i=1;i<=m;i++){cin>>x>>y>>z;Add(x,y,z);Add(y,x,z);}Dijkstra(s,d);return 0;}
1 0
原创粉丝点击