您的位置:首页 > 大数据 > 人工智能

POJ 3411 Paid Roads(DFS)

2015-03-20 21:14 387 查看
Paid Roads
Time Limit: 1000MSMemory Limit: 65536K
Total Submissions: 5708Accepted: 2054
DescriptionA 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.InputThe 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).OutputThe 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,意为如果a-b时,c之前没有到达过,则花费为r;若到达过,花费r,p均可,求1-n的最小花费
这道题一些边可以重复经历,因为使一些点已经遍历过后,在遍历其他点的时候可以选择花费更小的p,一些点的不能重复多次经历,这样会TLE,所以我们的标记数组要记下遍历的次数,>4跳出
    #include <iostream>    #include <cstdio>    #include <cstring>    #include <stdlib.h>    #include <algorithm>    #define N 20    #define inf 0x3f3f3f3f    using namespace std;    int b;    int n,m,ans;    struct node    {        int x,y,z;        int p,r;    }q;    void dfs(int a,int sum)    {        if(a==n)           {               ans=min(ans,sum);                return ;           }        for(int i=0;i<m;i++)        {            if(q[i].x==a && b[q[i].y]<=4)            {                if((!b[q[i].z]) ||(b[q[i].z] && q[i].r>q[i].r))                {                    b[q[i].y]++;                    dfs(q[i].y,sum+q[i].r);                    b[q[i].y]--;                }                else                {                     b[q[i].y]++;                    dfs(q[i].y, sum+q[i].p);                    b[q[i].y]--;                }            }        }    }    int main()    {       while(~scanf("%d%d",&n,&m))       {          for(int i=0;i<m;i++)           scanf("%d%d%d%d%d",&q[i].x,&q[i].y,&q[i].z,&q[i].p,&q[i].r);          ans=inf;          memset(b,0,sizeof(b));          dfs(1,0);           if(ans==inf)            printf("impossible\n");           else           printf("%d\n",ans);       }        return 0;    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: