Paid Roads(DFS)

11 篇文章 0 订阅
6 篇文章 0 订阅

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 aibiciPiRi (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 ≤ 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

解题思路:

题目大意是从A城到B城,如果之前经过C城那么只需要交P元,否则得交R元。问从第一个城市到最后一个城市最少交多少钱。这题一开始以为是最短路类型的,后来发现得用DFS做,为了减少费用,同一个城市可能经过多次,所以不能用Dijkstra来做了。用DFS枚举出所有的情况求出最小费用即可。难点在于限定一个城市最多可以访问几次,否则DFS将无限检索下去,一直纠结到底最多访问几次,网上说是最多访问3次,看了别人写的题解还是云里雾里的,希望有大牛可以解答一下。

AC代码:

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 20, INF = 999999999;
int  visited[maxn];
int n, m, mincost = INF;
struct node
{
    int a, b, c, p, r;
}route[maxn];
void Dfs(int a,int cost)
{
    if(a == n && cost < mincost)
    {
        mincost = cost;  // 到达n城并找到更少的花费就返回
        return;
    }
    for(int i = 1; i <= m; i++)
    {
        if(a == route[i].a && visited[route[i].b] <= 3)
        {
            visited[route[i].b]++;  // b城访问+1
            if(visited[route[i].c])     // 是否到过c城
                Dfs(route[i].b,route[i].p + cost);
            else
                Dfs(route[i].b,route[i].r + cost);
            visited[route[i].b]--;  //回溯
        }
    }
}
int main()
{
    int a, b, c, p, r, ans;
    scanf("%d%d", &n, &m);
    memset(visited, 0, sizeof(visited));
    for(int i = 1; i <= m; i++)
        scanf("%d%d%d%d%d", &route[i].a, &route[i].b, &route[i].c, &route[i].p, &route[i].r);
    Dfs(1,0);
    if(mincost == INF)
        printf("impossible\n");
    else
        printf("%d\n", mincost);
    return 0;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值