PTA emergency rescue (shortest path, Dijkstra algorithm)

L2-001 Emergency Rescue (25 points)

analysis:

The problem requires a wrong path. Obviously Freud's algorithm cannot be used.
Use Dijkstra's algorithm to record the source of the path, use DFS to find the path and store it in the vector container.

Code:

#include <bits/stdc++.h>
using namespace std;

int n, m, st, en, city[510], road[510][510], fast[510], ans1, ans2;
bool visit[510];
vector <int> sour[510];//每一个城市的最近路线来源
vector <int> ans3;
vector <int> temp;//在DFS中的暂时最佳路径

void init()//对数据进行初始化
{
    
    
	for (int i = 0; i<510; i++){
    
    
		for (int j = 0; j<510; j++){
    
    
			road[i][j] = 1e9;
		}
	}
	fill(fast, fast + 510, 1e9);
}

void Dijkstra()//迪杰斯特拉算法
{
    
    
	fast[st] = 0;
	while (1)
	{
    
    
		int chief = -1, mi = 1e9;
		for (int i = 0; i<n; i++)
		{
    
    
			if (!visit[i] && fast[i]<mi)
			{
    
    
				mi = fast[i];
				chief = i;
			}
		}

		if (chief == -1)return;
		visit[chief] = 1;

		for (int i = 0; i<n; i++)
		{
    
    
			int newfast = fast[chief] + road[chief][i];
			if (newfast<fast[i])
			{
    
    
				fast[i] = newfast;
				sour[i].clear();
			}
			if (newfast == fast[i])
			{
    
    
				sour[i].push_back(chief);
			}
		}
	}
}

void dfs(int a, int sum)//查找救援队最多的路线
{
    
    
	temp.push_back(a);
	sum += city[a];
	if (a == st)
	{
    
    
		ans1++;
		if (sum>ans2)
		{
    
    
			ans2 = sum;
			ans3 = temp;
		}
	}
	else
	{
    
    
		for (int i = 0; i<sour[a].size(); i++)
		{
    
    
			dfs(sour[a][i], sum);
		}
	}
	temp.pop_back();
}

int main()
{
    
    
	init();

	cin >> n >> m >> st >> en;
	for (int i = 0; i<n; i++)cin >> city[i];
	while (m--){
    
    
		int a, b, c;
		cin >> a >> b >> c;
		road[a][b] = road[b][a] = min(road[a][b], c);
	}

	Dijkstra();
	dfs(en, 0);

	cout << ans1 << ' ' << ans2 << endl;
	for (int i = ans3.size() - 1; i >= 0; i--){
    
    
		cout << ans3[i];
		if (i)cout << ' ';
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_43700916/article/details/88650428