Paid Roads POJ - 3411(计数标记型dfs)

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

思路:dfs+计数标记。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
using namespace std;
const int maxn=1e5+7;
#define inf 0x3f3f3f3f
int n,m;
int vis[40];
int ans;
struct Point
{
    int a,b,c,p,r;
}road[100];
void dfs(int u,int fee)
{
    if(ans<fee) return;
    if(u==n&&ans>fee)
    {
        ans=fee;
        return;
    }
    for(int i=1;i<=m;i++)
    {
        if(u==road[i].a&&vis[road[i].b]<=3)
        {
            int b=road[i].b;
            vis[b]++;
            if(vis[road[i].c])
            {
                dfs(b,road[i].p+fee);
            }
            else
            {
                dfs(b,road[i].r+fee);
            }
            vis[b]--;
        }
    }
}
int main(int argc, char const *argv[])
{
    #ifndef ONLINE_JUDGE
        freopen("in.txt","r",stdin);
        freopen("out.txt","w",stdout);
    #endif
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        memset(vis,0,sizeof(vis));
        vis[1]=1;
        ans=inf;
        int i=1;
        int tmp=m;
        while(tmp--)
        {
            scanf("%d%d%d%d%d",&road[i].a,&road[i].b,&road[i].c,&road[i].p,&road[i].r);
            i++;
        }
        dfs(1,0);
        if(ans==inf)
        {
            printf("impossible\n");
        }
        else
        {
            printf("%d\n",ans);
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40774175/article/details/81837220