Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 6167 | Accepted: 2246 |
Description
A network of m roads connects N cities (numbered from 1 toN). 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 roadi from city ai to citybi:
- in advance, in a city ci (which may or may not be the same asai);
- after the travel, in the city bi.
The payment is Pi in the first case andRi 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 ofai,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 cityN. 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
//还是借鉴了网上的提示,自己一开始觉得可以用BFS
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> /*题目刚开始有点不明白,in advance不明白,后来看别人的才明白的 有n座城市和m(1<=n,m<=10)条路。现在要从城市1到城市n。有些路是要收费的,从a城市到b城市,如果之前到过c城市,那么只要付P的钱,如果没有去过就付R的钱。求的是最少要花多少钱。 注意:路径是有向的。*/ //我觉得可以用BFS,但是最终还是用的DFS //之前走过某城市,是指只要在那条路上走过就行,不一定非得是邻近的那个城市,然后每个城市可以重复走,可以重复走的原因是有可能因为走过某个城市,费用就小点 #define MAXN 15 #define MAXM 15 #define MAXP 105 #define MAXR 105 #define MAX 1005 int a[MAXM]; int b[MAXM]; int c[MAXM]; int P[MAXM]; int R[MAXM]; int path[MAXM][MAXM]; int index[MAXM][MAXM]; int N = 0; int m = 0; int ans = MAX; typedef struct node { int x; int y; int front; int frontpay; int nonpay; }; node input[MAXN]; int visit[MAXM]; //因为允许重复走同一条路,因此不能只判断1 void init() { int i = 0; int j = 0; for (i = 0; i < MAXM;i++) { a[MAXM] = 0; b[MAXM] = 0; c[MAXM] = 0; P[MAXM] = 0; R[MAXM] = 0; for (j = 0; j < MAXM; j++) { path[i][j] = 0; index[i][j] = 0; } } ans = MAX; return; } void DFS(int x, int fee) { int i = 0; if (x == N) { if (ans > fee) { ans = fee; } return; } //开始遍历路 for (i = 1; i <= m; i++) { if ((x == input[i].x) && (visit[input[i].y]<=3)) //每个城市最多只能访问3次,至于这个3次值为了防止回路 { visit[input[i].y] += 1; if (0 != visit[input[i].front]) { DFS(input[i].y, fee + input[i].frontpay); } else { DFS(input[i].y, fee + input[i].nonpay); } //回溯 visit[input[i].y] -= 1; } } return ; } int main() { int i = 0; freopen("input.txt","r",stdin); init(); scanf("%d %d",&N,&m); for (i = 1; i<= m;i++) { scanf("%d %d %d %d %d", &a[i], &b[i], &c[i], &P[i], &R[i]); path[a[i]][b[i]] = 1; index[a[i]][b[i]] = 1; input[i].x = a[i]; input[i].y = b[i]; input[i].front = c[i]; input[i].frontpay = P[i]; input[i].nonpay = R[i]; } visit[1] = 1; //从城市1开始,费用是0 DFS(1, 0); if ( MAX == ans) { printf("impossible\n"); } else { printf("%d\n",ans); } return 0; }