L2-001 紧急救援 Dijkstra + 堆优化

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

输入格式:
输入第一行给出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 3
20 30 40 10
0 1 1
1 3 2
0 3 3
0 2 2
2 3 2
输出样例:
2 60
0 1 3

  • 本题用前向星+堆优化是完全没有必要的, 点数500完全可以开邻接矩阵
  • 思路来说 即保证最短路的前提下,找到那条含救援队伍最多的道路,即在dis相等的情况下,需要多开一个数组进行判断
  • 数组长度什么的都是乱开的Orz
  • 邻接矩阵好像有重边,注意输入判断
  • 以下代码难免限制于个人水平有所差错,仅提供参考
#include
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
//Constant area
const int MAXN=1000000;
const int MIN_INF=0x80000000;
const int MAX_INF=0x7fffffff;
//Variable area
int beg[265005];
int to[265005];
int nex[526005];
int weight[526005];
int a[526050];
bool vis[502605];
priority_queue<p> q;
int dis[5005];
int path[5005];
int mans[5005];
int cnt[500050];
int e,n,m,s,t;
struct p{
	int self;
	int val;
	int man;
	bool operator < (const p &b)const{
		if(val==b.val)
			return man>b.man;
		return val>b.val;
	}
};
//Initialization area
void init(){
	e=0;
	memset(beg,-1,sizeof(beg));
    return;
}
//Function area

void add(int x,int y,int z){
	nex[++e]=beg[x];
	beg[x]=e;
	to[e]=y;
	weight[e]=z;
}

void dijkstra(){
	q.push({s,0,a[s]});
	memset(dis,0x3f3f3f3f,sizeof(dis));
	dis[s]=0;
	memset(vis,0,sizeof(vis));
	memset(path,-1,sizeof(path));
	memset(mans,-1,sizeof(mans));
	memset(cnt,0,sizeof(cnt));
	mans[s]=a[s];
	while(q.size()){
		p now=q.top();
		q.pop();
//		if(vis[now.self])
//			continue;
		vis[now.self]=true;
		for(int i=beg[now.self];i!=-1;i=nex[i]){
			int too=to[i];
			if(vis[too])
				continue;
			if(dis[too]>dis[now.self]+weight[i]){
				dis[too]=dis[now.self]+weight[i];
				if(too==t)
					cnt[dis[too]]++;
				mans[too]=now.man+a[too];
				path[too]=now.self;
				q.push({too,dis[too],mans[too]});
			}else if(dis[too]==dis[now.self]+weight[i]){
				//there
				if(mans[too]<mans[now.self]+a[too]){
					if(too==t)//之所以能写在这里是因为重载运算符保证了更新情况的now.man必然大于之前的
						cnt[dis[too]]++;//去掉重载相等时的判断,则需要将该if放在there处
					path[too]=now.self;
					mans[too]=now.man+a[too];
					q.push({too,dis[too],mans[too]});
				}
			}
		}
	}
	cout<<cnt[dis[t]]<<" "<<mans[t]<<endl;
	int size[505];
	int dsize=0;
	for(int i=t;i!=s;i=path[i])
		size[++dsize]=i;
	cout<<s;
	for(int i=dsize;i!=0;i--)
		cout<<" "<<size[i];
	cout<<endl;
	return;
}
int main(){
    ios::sync_with_stdio(false);
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    init();
	cin>>n>>m>>s>>t;
	for(int i=0;i<n;i++)
		cin>>a[i];
	for(int i=1;i<=m;i++){
		int a,b,c;
		cin>>a>>b>>c;
		add(a,b,c);
		add(b,a,c);
	}
	dijkstra();
	return 0;
}

你可能感兴趣的:(PAT题目集合)