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
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
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
Source
思路:
剪枝一:如果长度大于ans,则返回
剪枝二:用minL[i][j]表示从源点走到城市i并且花费为j的时候经过的最短距离。若在后续的搜索中,再次走到i时,如果总路费恰好为j,且此时的路径长度已经超过 minL[i][j],则不必再走下去了。
剪枝二是最有效的,最强大的,没有则TLE
代码:
1 #include2 #include 3 #include 4 #include 5 using namespace std; 6 struct Road{ 7 int x,l,t; 8 Road (int xx = 0,int ll = 0,int tt = 0) : x(xx),l(ll),t(tt){} 9 };10 int k,n,r,s,d,l,t,ans,totalLen,totalCost,visited[105],minL[105][10005];11 vector vec[105];12 void dfs(int st){13 if(st == n){14 ans = min(ans,totalLen);15 return;16 }17 for(int i = 0;i < vec[st].size();i++){18 if(!visited[vec[st][i].x]){19 int cost = totalCost + vec[st][i].t;20 int len = totalLen + vec[st][i].l;21 if(cost > k || len >= ans || len >= minL[vec[st][i].x][cost])22 continue;23 totalLen += vec[st][i].l;24 totalCost += vec[st][i].t;25 visited[vec[st][i].x] = true;26 minL[vec[st][i].x][cost] = len;27 dfs(vec[st][i].x);28 totalLen -= vec[st][i].l;29 totalCost -= vec[st][i].t;30 visited[vec[st][i].x] = false;31 }32 }33 return;34 }35 int main(){36 scanf("%d%d%d",&k,&n,&r);37 for(int i = 1;i <= r;i++){38 scanf("%d%d%d%d",&s,&d,&l,&t);39 vec[s].push_back(Road(d,l,t));40 }41 for(int i = 0;i < 105;i++)42 for(int j = 0;j < 10005;j++)43 minL[i][j] = INT_MAX;44 ans = INT_MAX;45 totalLen = 0,totalCost = 0;46 visited[1] = true;47 dfs(1);48 ans == INT_MAX ? printf("-1\n") : printf("%d\n",ans);49 return 0;50 }