ROADS(深搜+邻接表)
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
The first line of the input contains the integer K, 0 <= K <= 10000, maximum number of coins that Bob can spend on his way.
The second line contains the integer N, 2 <= N <= 100, the total number of cities.
The third line contains the integer R, 1 <= R <= 10000, the total number of roads.
Each of the following R lines describes one road by specifying integers S, D, L and T separated by single blank characters :
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
Notice that different roads may have the same source and destination cities.
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
题意: 鲍勃要从1城市搬到N城市,给有向图及其权值(路费),鲍勃只有k过路费,求在花费k之内,从1到N的最短路
思路: 用邻接表表示有向图,深搜得最短路
邻接表来自这里
first[i]存储顶点i其中一条边的编号。
next[i]存储的是“编号为i的边”的“前一条边”的编号。
AC代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int k,n,r,minn;
int first[11000],next[11000],book[11000];
struct pp
{
int s,d,l,t;
}p[11000];
void dfs(int x,int s,int sum)
{
int i;
if(x==n)
{
if(s<minn)
minn=s;
return;
}
for(i=first[x];i!=-1;i=next[i])
{
if(book[p[i].d]||p[i].l+s>=minn||sum-p[i].t<0)
continue;
book[p[i].d]=1;
dfs(p[i].d,p[i].l+s,sum-p[i].t);
book[p[i].d]=0;
}
}
int main()
{
int i;
scanf("%d%d%d",&k,&n,&r);
memset(first,-1,sizeof(first));
for(i=0;i<r;i++)
{
scanf("%d%d%d%d",&p[i].s,&p[i].d,&p[i].l,&p[i].t);
next[i]=first[p[i].s];//邻接表
first[p[i].s]=i;
}
book[1]=1;
minn=999999;
dfs(1,0,k);
if(minn==999999)
printf("-1\n");
else
printf("%d\n",minn);
return 0;
}