POJ1797 道路可承受的最大重量(单源最短路径变形)

来源:互联网 发布:java 类构造器 编辑:程序博客网 时间:2024/06/04 20:03

有编号为1-N的地点,它们之间存在一些双向路径,每条路径有它的最大可承受重量,现在要从编号为1的地方向编号为N的地方运送货物。问运送的货物的最大重量。

采用类似最短路径的思想,把到达每个点的最短路径变成到达每个点的货物的最大重量,采用dijkstra或spfa运行一遍,把最后一个点的最大重量输出即可。

#include <iostream>#include <cstdio>#include <algorithm>#include <queue>using namespace std;const int N = 1005;const int E = 400005;const int MAX = 0xfffffff;struct Edge{int pnt;int weight;int next;}edge[E];int cur;int neigh[N];int n, e;int maxweight[N];bool vis[N];struct Qnode{int pnt;int weight;Qnode(int _pnt, int _weight): pnt(_pnt), weight(_weight){}bool operator < (const Qnode& node) const{return weight < node.weight;}};void init(){cur = 0;for (int i = 0; i < n; ++i) neigh[i] = -1;}void addedge(int beg, int end, int weight){edge[cur].pnt = end;edge[cur].weight = weight;edge[cur].next = neigh[beg];neigh[beg] = cur;++cur;}void dijkstra(){int pre, te, tmin, pnt;for (int i = 1; i < n; ++i){maxweight[i] = -MAX;vis[i] = false;}maxweight[0] = MAX;vis[0] = true;priority_queue<Qnode> pq;pq.push(Qnode(0, MAX));pre = 0;for (int i = 1; i < n; ++i){te = neigh[pre];while (te != -1){pnt = edge[te].pnt;if (!vis[pnt]){tmin = min(maxweight[pre], edge[te].weight);if (tmin > maxweight[pnt]){maxweight[pnt] = tmin;pq.push(Qnode(pnt, maxweight[pnt]));}}te = edge[te].next;}while (!pq.empty() && vis[pq.top().pnt]) pq.pop();pre = pq.top().pnt;vis[pre] = true;pq.pop();}}int main(){int T;int beg, end, weight;scanf("%d", &T);for (int t = 1; t <= T; ++t){scanf("%d%d", &n, &e);init();for (int i = 0; i < e; ++i){scanf("%d%d%d", &beg, &end, &weight);--beg;--end;addedge(beg, end, weight);addedge(end, beg, weight);}dijkstra();printf("Scenario #%d:\n", t);printf("%d\n\n", maxweight[n - 1]);}return 0;}


原创粉丝点击