L2-001 紧急救援 dijkstra

L2-001 紧急救援 (25 分)

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

输入格式:
输入第一行给出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

注意路径的读取以及救援队伍大小的判断,当相同的路径数时就要判断救援队伍的大小,最重要的还是这个的思想。

#include 
using namespace std;

const int N = 1010;

int n,m,s,d;
int person[N];//城市消防队数量
int a[N][N];//连通图
int roudnum[N];//路的条数
int dis[N];
bool st[N];
int pre[N];
int ans[N];//最大消防数
int path[N];//路径

void dijkstra()
{
    memset(dis, 0x3f, sizeof dis);
	memset(st, false, sizeof st);
	dis[s] = 0;
	ans[s] = person[s];
	roudnum[s] = 1;
    for(int i = 0;i < n - 1;i ++)//其余的城市
    {
        int t = -1;
        
        for (int j = 0; j < n; j++) {
            if (!st[j] && (t == -1 || dis[t] > dis[j]))
                t = j;
        }
        st[t] = true;//标记走过该点
        
        for (int j = 0; j < n; j++)
		{
			if (dis[j] > dis[t] + a[t][j]) {
				dis[j] = dis[t] + a[t][j];
				roudnum[j] = roudnum[t];
				pre[j] = t;
				ans[j] = ans[t] + person[j];
			}
			else {
				if (dis[j] == dis[t] + a[t][j]) {
					roudnum[j] += roudnum[t];
					if (ans[j] < person[j] + ans[t]) 
					{
						ans[j] = person[j] + ans[t];
						pre[j] = t;
					}
				}
			}
		}
    }
    cout << roudnum[d] << " "<< ans[d]<<endl;
    int q = d;
    int cnt = 0;
    while (q != s)
    {
        path[cnt++] = q;
        q = pre[q];
    }
    cout << s;
    for(int i = cnt - 1;i >=0;i --)
    {
        cout << " "<<path[i];
    }
    cout << endl;
}

int main(){
    
    cin>>n >> m>> s >> d;
    //s出发城市d目的地
    memset (a , 0x3f , sizeof a);
    for (int i = 0; i < n; i++)cin >> person[i];
	for (int i = 0; i < m; i++) { 
		int x, y, z;
		cin >> x >> y >> z;
		a[x][y] = a[y][x] = z;
	}
    dijkstra();
    return 0;
}

你可能感兴趣的:(图论,算法,c++)