poj3411

Paid Roads
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 6549   Accepted: 2427

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

Source

Northeastern Europe 2002, Western Subregion

大致题意:

有n座城市和m(1<=n,m<=10)条路。现在要从城市1到城市n。有些路是要收费的,从a城市到b城市,如果之前到过c城市,那么只要付P的钱,如果没有去过就付R的钱。求的是最少要花多少钱。

注意:路径是有向的。

#include<iostream>
#include<cstring>
using namespace std;
struct node{
    int a,b,c,p,r;
}e[11];//每条道路的付费规则
int n,m,mincost,vis[11];//城市数//道路数//最小总花费//记录城市的访问次数,每个城市最多经过3次
void dfs(int now,int fee){//now:当前所在城市,fee:当前方案的费用
    if(now==n&&mincost>fee){
        mincost=fee;return ;
    }
    for(int i=1;i<=m;i++){//枚举道路
        if(now==e[i].a&&vis[e[i].b]<=3){
            vis[e[i].b]++;
            if(vis[e[i].c])
                dfs(e[i].b,fee+e[i].p);    
            else
                dfs(e[i].b,fee+e[i].r);
            vis[e[i].b]--;//回溯
        }
    }
}
int main(){
    while(cin>>n>>m){
        memset(vis,0,sizeof vis);
        vis[1]=1;//从城市1出发,因此预记录到达1次
        mincost=2000;
        for(int i=1;i<=m;i++)
            cin>>e[i].a>>e[i].b>>e[i].c>>e[i].p>>e[i].r;
        dfs(1,0);
        if(mincost==2000)
            cout<<"impossible
";
        else
            cout<<mincost<<endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/shenben/p/5577665.html