UVA 10917 Walk Through the Forest
怒刷水题。。我说怎么会TLE 原来是自己记忆化搜索写挫了。。对比才知道dijkstra比bellman跑的快好多啊。
View Code
1 #include <iostream> 2 #include <cstring> 3 #include <queue> 4 #include <vector> 5 #include <cstdio> 6 #define maxn 1010 7 using namespace std; 8 typedef pair <int,int> pii; 9 int d[maxn],dp[maxn],visit[maxn]; 10 int first[maxn]; 11 vector<int> st,v,w,next; 12 int n,m,e; 13 14 void init() 15 { 16 e = 0; 17 st.clear(); 18 v.clear(); 19 w.clear(); 20 next.clear(); 21 memset(first,-1,sizeof(first)); 22 memset(visit,0,sizeof(visit)); 23 } 24 void add_edge(int a,int b,int c) 25 { 26 //w[e] = c; 27 w.push_back(c); 28 //st[e] = a; 29 st.push_back(a); 30 //v[e] = b; 31 v.push_back(b); 32 //next[e] = first[a]; 33 next.push_back(first[a]); 34 first[a] = e; 35 e++; 36 } 37 void Read_Graph() 38 { 39 int i,j,a,b,c; 40 e = 0; 41 for(i = 1;i <= m;i++) 42 { 43 scanf("%d%d%d",&a,&b,&c); 44 add_edge(a,b,c); 45 add_edge(b,a,c); 46 } 47 } 48 49 void dijkstra() 50 { 51 priority_queue < pii,vector<pii>,greater<pii> > q; 52 for(int i = 0;i <= n;i++) d[i] = 1 << 30; 53 d[2] = 0; 54 q.push(make_pair(0,2)); 55 while(!q.empty()) 56 { 57 while(!q.empty() && q.top().first > d[q.top().second]) q.pop(); 58 if(q.empty()) break; 59 int u = q.top().second; 60 q.pop(); 61 for(int i = first[u];i != -1;i = next[i]) 62 { 63 if(d[v[i]] > d[u] + w[i]) 64 { 65 d[v[i]] = d[u] + w[i]; 66 q.push(make_pair(d[v[i]],v[i])); 67 } 68 } 69 } 70 } 71 72 void Bellman_Ford() 73 { 74 int i,j; 75 for(i = 1;i <= n;i++) d[i] = 1 << 30; 76 d[2] = 0; 77 for(i = 1;i <= n;i++) 78 for(j = 0;j < e;j++) 79 d[v[j]] = d[st[j]] + w[j] < d[v[j]] ? d[st[j]] + w[j] : d[v[j]]; 80 } 81 82 int DP(int u) 83 { 84 int &ans = dp[u]; 85 if(visit[u]) return ans; 86 visit[u] = 1; 87 for(int i = first[u];i != -1;i = next[i]) 88 if(d[u] < d[v[i]]) 89 ans += DP(v[i]); 90 return ans; 91 } 92 93 void solve() 94 { 95 Read_Graph(); 96 dijkstra(); 97 //Bellman_Ford(); 98 int i,j; 99 memset(dp,0,sizeof(dp)); 100 dp[1] = 1; 101 printf("%d\n",DP(2)); 102 } 103 104 int main() 105 { 106 while(scanf("%d",&n),n) 107 { 108 scanf("%d",&m); 109 init(); 110 solve(); 111 } 112 return 0; 113 }