POJ 1724 ROADS(二维SPFA)

题目链接

用STL实现超时了,用普通队列500+,看到spfa,反应太迟钝了。

 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 #define INF 0x7fffffff
10 int d[101][10001];
11 int first[101];
12 bool in[101][10001];
13 int q1[10000001];
14 int q2[10000001];
15 int t,k,n;
16 struct node
17 {
18     int u,v,w,next,c;
19 }edge[10001];
20 void CL()
21 {
22     t = 1;
23     memset(first,-1,sizeof(first));
24 }
25 void add(int u,int v,int w,int c)
26 {
27     edge[t].u = u;
28     edge[t].v = v;
29     edge[t].w = w;
30     edge[t].c = c;
31     edge[t].next = first[u];
32     first[u] = t ++;
33 }
34 int spfa(int str,int end)
35 {
36     int x,y,v,i,j,ans,l,r;
37 
38     for(i = 1;i <= end;i ++)
39     {
40         for(j = 0;j <= k;j ++)
41         {
42             in[i][j] = 0;
43             d[i][j] = INF;
44         }
45     }
46     l = r = 1;
47     q1[1] = str;
48     q2[1] = 0;
49     in[str][0] = 1;
50     d[str][0] = 0;
51     while(l <= r)
52     {
53         x = q1[l];
54         y = q2[l];
55         l ++;
56         in[x][y] = 0;
57         for(i = first[x];i != -1;i = edge[i].next)
58         {
59             v = edge[i].v;
60             if(y + edge[i].c <= k)
61             {
62                 if(d[v][y+edge[i].c] > d[x][y] + edge[i].w)
63                 {
64                     d[v][y+edge[i].c] = d[x][y] + edge[i].w;
65                     if(!in[v][y+edge[i].c])
66                     {
67                         r ++;
68                         q1[r] = v;
69                         q2[r] = y+edge[i].c;
70                         in[v][y+edge[i].c] = 1;
71                     }
72                 }
73             }
74         }
75     }
76     ans = INF;
77     for(i = 0;i <= k;i ++)
78     {
79         ans = min(ans,d[end][i]);
80     }
81     return ans;
82 }
83 int main()
84 {
85     int m,sv,ev,w,c,ans,i;
86     scanf("%d%d%d",&k,&n,&m);
87     CL();
88     for(i = 1;i <= m;i ++)
89     {
90         scanf("%d%d%d%d",&sv,&ev,&w,&c);
91         add(sv,ev,w,c);
92     }
93     ans = spfa(1,n);
94     if(ans == INF)
95     printf("-1\n");
96     else
97     printf("%d\n",ans);
98     return 0;
99 }

 

posted @ 2013-07-06 19:08  Naix_x  阅读(280)  评论(0编辑  收藏  举报