poj 3411 Paid Roads(dfs)
Description
A network of m roads connects N cities (numbered from 1 to N). There may be more than one road connecting one city with another. Some of the roads are paid. There are two ways to pay for travel on a paid road i from city ai to city bi: in advance, in a city ci (which may or may not be the same as ai); after the travel, in the city bi. The payment is Pi in the first case and Ri in the second case. Write a program to find a minimal-cost route from the city 1 to the city N.
Input
The first line of the input contains the values of N and m. Each of the following m lines describes one road by specifying the values of ai, bi, ci, Pi, Ri (1 ≤ i ≤ m). Adjacent values on the same line are separated by one or more spaces. All values are integers, 1 ≤ m, N ≤ 10, 0 ≤ Pi , Ri ≤ 100, Pi ≤ Ri (1 ≤ i ≤ m).
Output
The first and only line of the file must contain the minimal possible cost of a trip from the city 1 to the city N. If the trip is not possible for any reason, the line must contain the word ‘impossible’.
Sample Input
4 5 1 2 1 10 10 2 3 1 30 50 3 4 3 80 80 2 1 2 10 10 1 3 2 10 50
Sample Output
110
Source
Northeastern Europe 2002, Western Subregion
直接dfs回溯找出最小的花费即可,以为n很小
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #pragma comment(linker, "/STACK:1024000000,1024000000") 2 #include<iostream> 3 #include<cstdio> 4 #include<cstring> 5 #include<cmath> 6 #include<math.h> 7 #include<algorithm> 8 #include<queue> 9 #include<set> 10 #include<bitset> 11 #include<map> 12 #include<vector> 13 #include<stdlib.h> 14 using namespace std; 15 #define ll long long 16 #define eps 1e-10 17 #define MOD 1000000007 18 #define N 26 19 #define inf 1e12 20 int n,m; 21 22 struct Node{ 23 int b,c,p,r; 24 }; 25 vector<Node> node[N]; 26 int ans; 27 int vis[N]; 28 void dfs(int u,int cost){ 29 vis[u]++; 30 if(cost>=ans) return; 31 if(u==n){ 32 if(cost<ans) 33 ans=cost; 34 return; 35 } 36 37 int size=node[u].size(); 38 for(int i=0;i<size;i++){ 39 int v=node[u][i].b; 40 if(vis[v]<=3){ 41 int t=99999; 42 if(vis[node[u][i].c] && t>node[u][i].p){ 43 t=node[u][i].p; 44 } 45 if(t>node[u][i].r){ 46 t=node[u][i].r; 47 } 48 dfs(v,t+cost); 49 vis[v]--; 50 } 51 } 52 53 54 55 } 56 int main() 57 { 58 while(scanf("%d%d",&n,&m)==2){ 59 for(int i=0;i<N;i++) node[i].clear(); 60 //scanf("%d%d",&n,&m); 61 for(int i=0;i<m;i++){ 62 int a,b,c,p,r; 63 scanf("%d%d%d%d%d",&a,&b,&c,&p,&r); 64 Node tmp; 65 //tmp.a=a; 66 tmp.b=b; 67 tmp.c=c; 68 tmp.p=p; 69 tmp.r=r; 70 node[a].push_back(tmp); 71 } 72 memset(vis,0,sizeof(vis)); 73 ans=99999; 74 dfs(1,0); 75 if(ans==99999) printf("impossible\n"); 76 else printf("%d\n",ans); 77 } 78 return 0; 79 }