Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 7017 | Accepted: 2599 |
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
1:如果以前经过c城市,那么就在c城市付费。。
2:如果没有经过,那么就在b城市付费。。
还有注意题目中的数据为m<10,所以每个点最多走3次。。
因为成环的话那么最少3个点,则最少3路。所以最多走3次。。。
故应用int vis[ manx]。。。
然后dfs回溯。。
#include <stdio.h>
#include <string.h>
#define INF 0x3f3f3f3f
struct node
{
int a,b,c,p,r;
}s[20];
int vis[20];
int n, m;
int ans;
void dfs( int x, int cost)
{
if( x == n && ans > cost)
{
ans = cost;return;
}
for( int i = 0; i < m; i++)
{
if(s[i].a == x &&vis[s[i].b] < 3)
{
vis[s[i].b]++;
if(vis[s[i].c])
dfs(s[i].b,cost+s[i].p);
else dfs(s[i].b, cost+s[i].r);
vis[s[i].b]--;
}
}
}
int main()
{
scanf("%d%d", &n,&m);
for( int i = 0; i < m; i++)
{
scanf("%d%d%d%d%d",&s[i].a,&s[i].b,&s[i].c,&s[i].p,&s[i].r);
}
memset(vis, 0,sizeof(vis));
ans = INF;
vis[1] = 1;
dfs(1, 0);
if(ans == INF) printf("impossible\n");
else printf("%d\n",ans);
}