roads (广搜 优先队列 邻接表)
(广搜 优先队列 邻接表)
Description
N cities named with numbers 1 ... N are connected with one-way roads. Each road has two parameters associated with it : the road length and the toll that needs to be paid for the road (expressed in the number of coins).
Bob and Alice used to live in the city 1. After noticing that Alice was cheating in the card game they liked to play, Bob broke up with her and decided to move away - to the city N. He wants to get there as quickly as possible, but he is short on cash.
We want to help Bob to find the shortest path from the city 1 to the city N that he can afford with the amount of money he has.
Input
- S is the source city, 1 <= S <= N
- D is the destination city, 1 <= D <= N
- L is the road length, 1 <= L <= 100
- T is the toll (expressed in the number of coins), 0 <= T <=100
Output
The first and the only line of the output should contain the total length of the shortest path from the city 1 to the city N whose total toll is less than or equal K coins.
If such path does not exist, only number -1 should be written to the output.
Sample Input
5
6
7
1 2 2 3
2 4 3 3
3 4 2 4
1 3 4 1
4 6 2 1
3 5 2 0
5 4 3 2
Sample Output
11
题意
两点之间不但有距离 还有花费,给你一些点之间的信息,和所拥有的的总钱数,求从起点到终点的最短距离,并且不超过总发费(当然花费越少越好)
分析
用优先队列进行广搜,优先规则是 长度 然后是 花费,满足花费不超过总钱数,搜最短的距离。
代码
#include<iostream>
#include<stdio.h>
#include<queue>
#include<string.h>
using namespace std;
struct node
{
int value;
int len;
int to;
int next;
friend bool operator < (node a,node b)
{
if(a.len!=b.len)
return a.len>b.len;
else
return a.value>b.value;
}
} edge[10010];
int cnt=0;
int head[110];
int sumValue;
int cityN;
int edgeN;
void add(int a,int b,int c,int d)///邻接链表
{
edge[cnt].to=b;
edge[cnt].len=c;
edge[cnt].value=d;
edge[cnt].next=head[a];
head[a]=cnt++;
}
int bfs()
{
node t;
t.to=1;
t.len=0;
t.value=0;
priority_queue<node>q;
q.push(t);
while(!q.empty())
{
t=q.top();
q.pop();
if(t.to==cityN)
return t.len;
for(int i=head[t.to]; i!=-1; i=edge[i].next)
{
if(t.value+edge[i].value<=sumValue)
{
node temp;
temp.len=t.len+edge[i].len;
temp.value=t.value+edge[i].value;
temp.to=edge[i].to;///保存要搜的下一个点
q.push(temp);
}
}
}
return -1;
}
int main()
{
while(~scanf("%d",&sumValue))
{
memset(head,-1,sizeof(head));
cnt=0;
scanf("%d%d",&cityN,&edgeN);
for(int i=0; i<edgeN; i++)
{
int a,b,c,d;
scanf("%d%d%d%d",&a,&b,&c,&d);
add(a,b,c,d);
}
printf("%d\n",bfs());
}
return 0;
}