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

有编号为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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值