其他分享
首页 > 其他分享> > A1003 Emergency (25 分)

A1003 Emergency (25 分)

作者:互联网

1003 Emergency (25 分)

解题思路

       在学习过《算法笔记》之后,这算是一道毫无难度的题,完全可以套用算法笔记上关于迪杰斯特拉算法的模板,当然也因为是最早期的题,所以被研究的很透彻了。
       没有什么需要注意的细节,唯一需要的就是熟读一遍《算法笔记》的相关章节。

AC代码

#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
const int maxn = 501;
const int INF = 0x7ffffff;
struct node {
	int dis, id;
	node () {}
	node(int _dis, int _id): dis(_dis), id(_id) {}
};
vector<node> adj[maxn];
vector<int> pre[maxn], tempPath, cost;
int rnum = 0, maxr = 0, d[maxn], n, m, st, se;
bool vis[maxn] = {false};
void dijstra(int s) {
	fill(d, d + maxn, INF);
	d[s] = 0;
    for (int i = 0; i < n; ++i)
    {
    	int u = -1, MIN = INF;
    	for (int j = 0; j < n; ++j) {
    		if (vis[j] == false && d[j] < MIN) {
    			u = j;
    			MIN = d[j];
    		}
    	}
    	if (u == -1) return;
    	vis[u] = true;
    	for (int i = 0; i < adj[u].size(); ++i) {
    		int v = adj[u][i].id;
            if (d[u] + adj[u][i].dis < d[v]) {
            	d[v] = d[u] + adj[u][i].dis;
            	pre[v].clear();
            	pre[v].push_back(u);
            }
            else if (d[v] == d[u] + adj[u][i].dis)
            	pre[v].push_back(u);
    	}
    }
}
void DFS(int v) {
	if (v == st) {
		rnum++;
		tempPath.push_back(v);
		int tempcost = 0;
		for (int i = 0; i < tempPath.size(); ++i) {
			tempcost += cost[tempPath[i]];
		}
		if (tempcost > maxr) maxr = tempcost;
		tempPath.pop_back();
	}
	tempPath.push_back(v);
	for (int i = 0; i < pre[v].size(); ++i) {
		DFS(pre[v][i]);
	}
	tempPath.pop_back();
}
int main() {
    scanf("%d %d %d %d", &n, &m, &st, &se);
    cost.resize(n);
    for (int i = 0; i < n; ++i) {
    	scanf("%d", &cost[i]);
    }
    for (int i = 0; i < m; ++i) {
    	int a, b, l;
    	scanf("%d %d %d", &a, &b, &l);
    	adj[a].push_back(node(l, b));
    	adj[b].push_back(node(l, a));
    }
    dijstra(st);
    DFS(se);
    printf("%d %d\n", rnum, maxr);
    return 0;
}

标签:25,Emergency,int,back,A1003,++,tempPath,adj,dis
来源: https://blog.csdn.net/LinxRds/article/details/89035957