POJ 1724 ROADS

127 篇文章 0 订阅
7 篇文章 0 订阅

 /*
可以算作是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;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值