POJ 3411 Paid Roads(DFS)

题目链接

点和边 都很少,确定一个界限,爆搜即可。判断点到达注意一下,如果之前已经到了,就不用回溯了,如果之前没到过,要回溯。

 1 #include <cstring>

 2 #include <cstdio>

 3 #include <string>

 4 #include <iostream>

 5 #include <algorithm>

 6 #include <vector>

 7 #include <queue>

 8 using namespace std;

 9 struct node

10 {

11     int a,b,c,p,r,next;

12 } edge[101];

13 int first[21],t,minz;

14 int o[21],n;

15 void CL()

16 {

17     t = 1;

18     memset(first,-1,sizeof(first));

19     memset(o,0,sizeof(o));

20 }

21 void add(int a,int b,int c,int p,int r)

22 {

23     edge[t].a = a;

24     edge[t].b = b;

25     edge[t].c = c;

26     edge[t].p = p;

27     edge[t].r = r;

28     edge[t].next = first[a];

29     first[a] = t ++;

30 }

31 void dfs(int x,int sum)

32 {

33     int i,v,s,z;

34     if(sum >= minz)

35         return ;

36     if(x == n)

37     {

38         minz = min(sum,minz);

39         return ;

40     }

41     for(i = first[x]; i != -1; i = edge[i].next)

42     {

43         v = edge[i].b;

44         s = edge[i].c;

45         z = 0;

46         if(o[s])

47         {

48             if(o[v])

49             z = 1;

50             else

51             o[v] = 1;

52             dfs(v,sum+edge[i].p);

53             if(z == 0)

54             o[v] = 0;

55         }

56         else

57         {

58             if(o[v])

59             z = 1;

60             else

61             o[v] = 1;

62             dfs(v,sum+edge[i].r);

63             if(z == 0)

64             o[v] = 0;

65         }

66     }

67     return ;

68 }

69 int main()

70 {

71     int i,m,sum;

72     int a,b,c,p,r;

73     scanf("%d%d",&n,&m);

74     CL();

75     sum = 0;

76     for(i = 1; i <= m; i ++)

77     {

78         scanf("%d%d%d%d%d",&a,&b,&c,&p,&r);

79         add(a,b,c,p,r);

80         sum += r;

81     }

82     minz = sum+1;

83     o[1] = 1;

84     dfs(1,0);

85     if(minz == sum+1)

86         printf("impossible\n");

87     else

88         printf("%d\n",minz);

89     return 0;

90 }

 

你可能感兴趣的:(poj)