Paid Roads
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
题意:
有n个城市m条路线,每条路线有5个值,a,b,c,p,r表示从a城到b城,如果到过c城,收费p元,否则收费r元(p <= r)。现在从1到n,求最小花费。
分析:
由于n,m的大小只有10,所以我们可以DFS枚举出所有的路径然后求出最小值。
由于要看是否走过c,所以我们要记录已达的城市
注意:在这个题目中,每个城市可以经过多次,且每条边也可能走多次
(我就是没有想到每条边还可能走多次。。。卡了一上午)这个要好好想想
在记录经过的路径时我们不能用bool vis[]表示是否经过,因为可能经过两次后,在dfs回溯时可能被一次就还原了。所以我们要用int vis[]来记录经过的次数,由于m<= 10所以每个点最多经过3次,以这个条件防止死循环。
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int maxn = 15;
struct edge
{
int v,c,p,r,next;
}edges[maxn];
int head[maxn];
int vispath[maxn];
//bool vism[maxn];
int n,m,e,ans;
void addedge(int u,int v,int c,int p,int r)
{
edges[e].v = v; edges[e].c = c; edges[e].p = p; edges[e].r = r;
edges[e].next = head[u];
head[u] = e++;
}
void dfs(int u,int cost)
{
if(cost > ans) return;
if(u == n)
{
if(cost < ans) ans = cost;
return;
}
for(int i=head[u];i!=-1;i=edges[i].next)
{
int v = edges[i].v;
if(vispath[v]<=3)
{
vispath[v]++;
if(vispath[edges[i].c]>0) dfs(v,cost+edges[i].p);
else dfs(v,cost+edges[i].r);
vispath[v]--;
}
}
}
int main()
{
int u,v,c,p,r;
while(scanf("%d%d",&n,&m)!=EOF)
{
memset(head,-1,sizeof(head));
e = 0;
for(int i=0;i<m;i++)
{
scanf("%d%d%d%d%d",&u,&v,&c,&p,&r);
addedge(u,v,c,p,r);
}
ans = 99999999;
memset(vispath,0,sizeof(vispath));
memset(vism,false,sizeof(vism));
vispath[1] = 1;
dfs(1,0);
if(ans < 99999999) printf("%d\n",ans);
else printf("impossible\n");
}
return 0;
}