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
/* 用dfs. */ #include <iostream> #include <cstdio> #include <cstring> #define maxn 28 #define inf 0x3f3f3f3f int vis[maxn]; int first[maxn],vv[maxn],w1[maxn],w2[maxn],nxt[maxn],p[maxn]; int dis[maxn]; int n,e; inline int min(int a,int b) { return a>b?b:a; } void dfs(int x,int cost) { if(cost > dis[n]) return; if(x == n) { dis[x] = min(dis[x],cost); return; } for(int i = first[x];i != -1;i = nxt[i]) { int v = vv[i]; if(vis[v] <= 3) { vis[v]++; if(vis[p[i]]) dfs(v,cost+w1[i]); else dfs(v,cost+w2[i]); vis[v]--; } } } void addEdge(int u,int v,int ww1,int ww2,int pos) { vv[e] = v; w1[e] = ww1; w2[e] = ww2; p[e] = pos; nxt[e] = first[u]; first[u] = e++; } int main() { //freopen("in.txt","r",stdin); int m; while(scanf("%d%d",&n,&m)==2) { e = 0; memset(dis,0x3f,sizeof(dis)); memset(p,0,sizeof(p)); memset(first,-1,sizeof(first)); memset(vis,0,sizeof(vis)); dis[1] = 0; vis[1] = 1; for(int i=1;i<=m;i++) { int a,b,c,cost1,cost2; scanf("%d%d%d%d%d",&a,&b,&c,&cost1,&cost2); addEdge(a,b,cost1,cost2,c); } dfs(1,0); if(dis[n] != inf) printf("%d\n",dis[n]); else printf("impossible\n"); } return 0; }