UVA10917 Walk Through the Forest (dijkstra + dfs)
2017-10-19 21:35
405 查看
题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1858
题意: jimmy每天想走不同的路回家,但他也不想太晚回家,因此他不会走回头路,换句话说,他只会沿着(A,B)这样的道路走,存在一条从B出发回家的路径,比所有从A出发回家的路径都短,求一共有多少条这样的路径。
思路:dijkstra求从家到各点的单源最短路径,然后dfs求路径即可。
题意: jimmy每天想走不同的路回家,但他也不想太晚回家,因此他不会走回头路,换句话说,他只会沿着(A,B)这样的道路走,存在一条从B出发回家的路径,比所有从A出发回家的路径都短,求一共有多少条这样的路径。
思路:dijkstra求从家到各点的单源最短路径,然后dfs求路径即可。
#include <cstdio> #include <queue> #include <cstring> #include <algorithm> #define LL long long #define inf 1LL << 60 using namespace std; const int maxn = 1e6+ 10; int N,M,cnt; int head[maxn],vis[1100],dp[1100]; LL dist[maxn]; struct Edge{ int to,w,next; }edge[maxn]; struct node{ int dis,v; friend bool operator <(node A, node B){ return A.dis > B.dis; } }; void add(int u, int v, int w){ edge[cnt].to = v; edge[cnt].w = w; edge[cnt].next = head[u]; head[u] = cnt ++; } void dijkstra(int x){ for(int i = 1; i <= N; i ++ ) dist[i] = inf,vis[i] = 0; dist[x] = 0; priority_queue<node > q; node p; p.dis = 0, p.v = x; q.push(p); while(!q.empty()){ p = q.top(); q.pop(); if(vis[p.v]) continue; vis[p.v] = 1; for(int i = head[p.v]; i != -1; i = edge[i].next){ int v = edge[i].to; if(dist[v] > dist[p.v] + edge[i].w){ dist[v] = dist[p.v] + edge[i].w; node no; no.dis = dist[v], no.v = v; q.push(no); } } } } int dfs(int x){ if(x == 2) return 1; if(dp[x]) return dp[x]; int ret = 0; for(int i = head[x]; i != -1; i = edge[i].next){ int v = edge[i].to; if(dist[x] > dist[v]) ret += dfs(v); } return dp[x] = ret; } int main(){ while(~scanf("%d",&N) && N){ scanf("%d",&M); memset(head,-1,sizeof(head)); int u,v,w; cnt = 0; for(int i = 1; i <= M; i ++){ scanf("%d%d%d",&u,&v,&w); add(u,v,w); add(v,u,w); } dijkstra(2); memset(dp,0,sizeof(dp)); printf("%d\n",dfs(1)); } return 0; }
相关文章推荐
- UVa 10917 - Walk Through the Forest(Dijkstra + DFS)
- UVA 10917 Walk Through the Forest(dijkstra+DAG上的dp)
- UVa10917 - Walk Through the Forest(dijkstra+dp)
- uva 10917 - Walk Through the Forest(Dijkstra+Dp)
- UVA 10917 Walk Through the Forest(Dijkstra+DAG动态规划)
- UVA-10917 Walk Through the Forest (dijkstra+DP)
- 【最短路+dfs+dijkstra】杭电 hdu 1142 A Walk Through the Forest
- uva 10917 Walk Through the Forest(最短路)
- UVA 10917 Walk Through the Forest(最短路+dp)
- Walk Through the Forest UVA - 10917 DAG上的图
- HDU 1142 A Walk Through the Forest(Dijkstra+Dfs(第一次用记忆化搜索))
- UVA 10917 Walk Through the Forest
- uva 10917 Walk Through the Forest
- uva 10917 Walk Through the Forest
- UVa10917 - Walk Through the Forest(单源最短路径及动态规划)
- UVA10917 Walk Through the Forest
- HDU-1142-A Walk Through the Forest(Dijkstra+dfs)
- UVA 10917 - Walk Through the Forest(dijstra)
- UVa 10917 A Walk through the forest
- Uva 10917 Walk Through the Forest(DAG拓扑排序)