题目大意:
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;
}