<----my github

POJ 1724 Roads 道路

问题的链接在这里

与一般的最短路径问题不同,本题是在给定的经济条件约束下寻求最短路径。可以使用BFS简单的完成。
关键在于这里采用什么样的数据结构来进行操作。
为了方便,使用传统的二维数组数据结构也是可以的。
这里采用一维数组,每个元素是一个road,包含题目中涉及到的DLT三个元素,并额外用一个数组表明这条road的source城市的相邻的road(如A到B是路径1,A到C是路径2,除此之外没有A到其他节点的路径了,那么路径1响铃的路径是路径2,路径2相邻的路径是null)。
BFS的过程很简单,从1号节点开始用队列的方式不断添加节点,如果节点的花费超过了限制就舍弃掉这个节点,因为是BFS所以如果找到节点的话一定是最优解。
详细代码如下:

点击查看代码
#include<iostream>
#include<queue>
#include<ctime>
#define MAX 10010
/*
	*本题是要在经济耗费小于给定值的条件下找到通往N城市的最短距离耗费
	*可以使用BFS来获得最小的耗费
*/
using namespace std;
struct road {
	int d;	//destination
	int l;	//length
	int t;	//cost
	int next;	//类似于这条路的“兄弟”,将来用于搜索一个城市并向队列中加入节点
}roads[2*MAX];
//向队列中加入的节点的数据结构,包含已经花费的长度和开销
struct node {
	int cost;
	int length;
	int city;	//节点代表的城市号
};
struct node_greater {
	bool operator() (const node& a, const node& b)
	{
		return a.length > b.length;	// 小顶堆
	}
};
int K, N, R;
int index = 0;
int nextArray[MAX];	//下一个
//用优先队列来保证最后的答案是最小的
priority_queue<node,vector<node>,node_greater> queueExplore;
int BFS() {
	node temp,temp2;
	temp.length = temp.cost = 0;
	temp.city = 1;
	queueExplore.push(temp);
	while (!queueExplore.empty()) {
		temp = queueExplore.top();
		queueExplore.pop();
		int v = temp.city;
		if(v == N){
			return temp.length;
		}
		//遍历每一条顶点对应的边
		for (int i = nextArray[v]; i != -1; i = roads[i].next) {
			if (temp.cost + roads[i].t <= K) {
				temp2.cost = temp.cost + roads[i].t;
				temp2.length= temp.length + roads[i].l;
				temp2.city = roads[i].d;
				queueExplore.push(temp2);
			}
		}
	}
	return -1;
}
int main(){
	cin >> K >> N >> R;
	int cost;
	int source;
	memset(nextArray, -1, sizeof(nextArray));
	//从输入中获取边的信息
	for (int k = 0; k < R; k++) {
		cin >> source >> roads[k].d >> roads[k].l >> roads[k].t;
		roads[k].next = nextArray[source];
		nextArray[source] = k;
	}
	cost = BFS();
	cout << cost << endl;
	return 0;
}
posted @ 2022-01-13 22:06  CinqueOrigin  阅读(96)  评论(0)    收藏  举报