POJ 1724 ROADS

88 篇文章 0 订阅
9 篇文章 1 订阅

题目大意:

Bob要从City1到Cityn(想知道原因就去认真读题~~)他想走最短的路到Cityn,但是走任何一条路都需要花钱。

他只有R元钱,问他能走的最短路径是多长?


解题思路:

基于优先队列的BFS,搜索寻找最短路径,当路径长度相同时输出花费最少的。



下面是代码:

#include <stdio.h>
#include <vector>
#include <queue>
#include <string.h>
using namespace std;
struct node
{
    int to,w,c,next;
} edge[10005];
int head[105],cnt,r,n,m;
struct node1
{
    int dis,fa,cost1;
    bool vis[105];
    bool operator <(const node1 &a)const
    {
        if(a.dis==dis)return a.cost1<cost1;
        return a.dis<dis;
    }
};
void addedge(int u,int v,int w,int c)
{
    edge[cnt].to=v;
    edge[cnt].w=w;
    edge[cnt].c=c;
    edge[cnt].next=head[u];
    head[u]=cnt++;
}
int main()
{
    int u,v,l,t;
    scanf("%d%d%d",&r,&n,&m);
    memset(head,-1,sizeof(head));
    for(int i=0; i<m; i++)
    {
        scanf("%d%d%d%d",&u,&v,&l,&t);
        addedge(u,v,l,t);
    }
    priority_queue<struct node1,vector <node1>,less<node1> >q;
    struct node1 temp,xtemp;
    memset(temp.vis,false,sizeof(temp.vis));
    temp.vis[1]=true;
    temp.fa=1;
    temp.dis=0;
    temp.cost1=0;
    q.push(temp);
    while(!q.empty())
    {
        temp=q.top();
        q.pop();
        //printf("%d %d %d\n",temp.fa,temp.dis,temp.cost1);
        if(temp.cost1>r)continue;
        if(temp.fa==n)break;
        int p=head[temp.fa];
        while(p!=-1)
        {
            xtemp=temp;
            if(!xtemp.vis[edge[p].to])
            {
                xtemp.vis[edge[p].to]=true;
                xtemp.fa=edge[p].to;
                xtemp.dis+=edge[p].w;
                xtemp.cost1+=edge[p].c;
                q.push(xtemp);
            }
            p=edge[p].next;
        }
    }
    if(temp.cost1>r)puts("-1");
    else if(temp.fa!=n)puts("-1");
    else printf("%d\n",temp.dis);
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值