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 ifrom city ai to 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
|
提示
题意:给出m(1<=m<=10)条有向路径,求出从1到n(1<=n<=10)标号的城市所需要最少的花费,如果无法到达输出"impossible"。从城市ai到城市bi的花费是这样算的:
如果之前去过城市ci,所需花费为Pi。
否则所需花费为Ri。
思路:
这题本质上是求同一个节点可以经过多次的最短路,n最大为10,那么一个节点最多经过3次,所以保证一个节点最多遍历3次进行DFS就是答案。
为什么是三次呢?如图所示:
如果需要全部遍历的话,那么中间那个节点最多遍历三次。m最大为10,这是最极限的情况。
示例程序
Source Code
Problem: 3411 Code Length: 1202B
Memory: 388K Time: 0MS
Language: GCC Result: Accepted
#include <stdio.h>
#include <string.h>
struct
{
int p,r,v,t,next;
}w[10];
int h[10],ans,vis[10];
void insert(int numw,int u,int v,int t,int p,int r)
{
w[numw].v=v;
w[numw].t=t;
w[numw].p=p;
w[numw].r=r;
w[numw].next=h[u];
h[u]=numw;
}
void dfs(int t,int n,int sum)
{
int i;
if(sum>=ans)
{
return;
}
if(t==n-1)
{
if(ans>sum)
{
ans=sum;
}
return;
}
for(i=h[t];i!=-1;i=w[i].next)
{
if(vis[w[i].v]<3)
{
vis[w[i].v]++;
if(vis[w[i].t]!=0)
{
dfs(w[i].v,n,sum+w[i].p);
}
else
{
dfs(w[i].v,n,sum+w[i].r);
}
vis[w[i].v]--;
}
}
}
int main()
{
int n,m,i,u,v,t,p,r;
scanf("%d %d",&n,&m);
memset(h,-1,sizeof(h));
for(i=1;m>=i;i++)
{
scanf("%d %d %d %d %d",&u,&v,&t,&p,&r);
insert(i-1,u-1,v-1,t-1,p,r);
}
ans=1e9+7;
memset(vis,0,sizeof(vis));
vis[0]=1;
dfs(0,n,0);
if(ans==1e9+7)
{
printf("impossible");
}
else
{
printf("%d",ans);
}
return 0;
}