/*
可以算作是A*算法了,利用priority_queue实现
*/
#include <iostream>
#include <queue>
#define MAX_N 100
#define MAX_K 10000
using namespace std;
struct node
{
int countv;
int data[MAX_N * MAX_N + 5][3]; //id, dist, coins
}nodes[MAX_N + 1];
int K, noden, edgen;
int minDist = INT_MAX;
int minCostDist[MAX_N + 1][MAX_K + 1]; //minCostDist[i][k]表示从1走到i花费k需要的最短路径长度
struct elem
{
int id, dist, cost;
};
struct compare
{
//返回false,e1才会排在前面
bool operator()(const elem &e1, const elem &e2)
{
return (e1.dist == e2.dist) ? e1.cost >= e2.cost : e1.dist > e2.dist;
}
};
priority_queue<elem, vector<elem>, compare> bfsq;
void bfs()
{
elem startNode, curNode, newNode;
startNode.cost = 0; startNode.dist = 0; startNode.id = 1;
minCostDist[1][0] = 0;
bfsq.push(startNode);
while(!bfsq.empty())
{
curNode = bfsq.top(); bfsq.pop();
if(curNode.id == noden)
{
if(curNode.dist < minDist)
minDist = curNode.dist;
return;
}
int num = nodes[curNode.id].countv;
for(int i = 1; i <= num; i++)
{
newNode.id = nodes[curNode.id].data[i][0];
newNode.dist = curNode.dist + nodes[curNode.id].data[i][1];
newNode.cost = curNode.cost + nodes[curNode.id].data[i][2];
int minv = minCostDist[newNode.id][newNode.cost];
if(newNode.cost <= K && newNode.dist < minv)
{
minCostDist[newNode.id][newNode.cost] = newNode.dist;
bfsq.push(newNode);
}
}
}
}
int main()
{
int i, from, to, dist, coins;
scanf("%d%d%d", &K, &noden, &edgen);
for(i = 1; i <= edgen; i++)
{
scanf("%d%d%d%d", &from, &to, &dist, &coins);
int pos = ++nodes[from].countv;
nodes[from].data[pos][0] = to;
nodes[from].data[pos][1] = dist;
nodes[from].data[pos][2] = coins;
}
memset(minCostDist, 5, sizeof(minCostDist));
bfs();
if(minDist != INT_MAX) printf("%d/n", minDist);
else printf("-1/n");
return 0;
}
POJ 1724 ROADS
最新推荐文章于 2024-08-29 16:37:54 发布