HDU - 1142 - A Walk Through the Forest
2017-07-24 23:04
387 查看
题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=1142
题目的意思真的十分的难理解,刚开始以为是让求最短路径有几条,后来看了题解才知道是让求 1 到 2 的路上不绕远路的路有几条,就是每一步都要更接近终点一些。就是每次要从A到B点前要先判断B点距离终点是否比A点距离终点要来的近,然后A到B直接必须是有路的。
最短路的话用Dijkstra或者spfa都可以写,然后图是无向图,顶点也不是很多,可以直接用邻接矩阵来存,算出2到其他各点的最短路,再进行搜索,从1开始,2结束,然后有很多地方会重复搜,可以标记一下,就是用记忆化搜索。
题目的意思真的十分的难理解,刚开始以为是让求最短路径有几条,后来看了题解才知道是让求 1 到 2 的路上不绕远路的路有几条,就是每一步都要更接近终点一些。就是每次要从A到B点前要先判断B点距离终点是否比A点距离终点要来的近,然后A到B直接必须是有路的。
最短路的话用Dijkstra或者spfa都可以写,然后图是无向图,顶点也不是很多,可以直接用邻接矩阵来存,算出2到其他各点的最短路,再进行搜索,从1开始,2结束,然后有很多地方会重复搜,可以标记一下,就是用记忆化搜索。
#include<iostream> #include<string.h> #include<stdio.h> #include<queue> using namespace std; const int inf = 2147483647,maxn = 1010; int n,m,mp[maxn][maxn],dist[maxn],ans[maxn]; struct node { int num,dist; node(int a,int b) { num = a; dist = b; } friend bool operator < (node a,node b) { return a.dist > b.dist; } }; void dij_up() { node s(2,0) ; priority_queue<node>q; q.push(s); while(!q.empty()) { s = q.top(); q.pop(); if(s.dist>dist[s.num]) continue; for(int i=1;i<=n;i++) { if(mp[s.num][i]<inf&&dist[i]>dist[s.num]+mp[s.num][i]) { dist[i] = dist[s.num]+mp[s.num][i]; q.push(node(i,dist[i])); } } } } int dfs(int x) { if(ans[x]) return ans[x]; int sum = 0; for(int i=1;i<=n;i++) { if(mp[x][i] < inf && dist[i] < dist[x]) sum += dfs(i); } return ans[x] = sum; } int main() { while(scanf("%d",&n)&&n) { for(int i=0;i<=n;i++) { dist[i] = inf; for(int j = 0;j<=n;j++) { mp[i][j] = inf; } } memset(ans,0,sizeof ans); scanf("%d",&m); for(int i=0;i<m;i++) { int a,b,c; scanf("%d%d%d",&a,&b,&c); mp[a][b] = mp[b][a] = c; } dist[2] = 0; dij_up(); ans[2] = 1; dfs(1); printf("%d\n",ans[1]); } return 0; }
相关文章推荐
- HDU 1142 A Walk Through the Forest(spfa最短路+dfs记忆化搜索)
- HDU 1142 A Walk Through the Forest (dijkstra+记忆化搜索)
- hdu 1142 A Walk Through the Forest(最短路+记忆化搜索)
- hdu 1142 A Walk Through the Forest
- hdu1142 - A Walk Through the Forest(SPFA+记忆化搜索)
- hdu 1142 A Walk Through the Forest (最短路+dfs )
- hdu 1142 A Walk Through the Forest
- HDU1142-A Walk Through the Forest(记忆化搜索+SPFA)
- hdu 1142 A Walk Through the Forest(dijkstra)
- HDU 1142 A Walk Through the Forest (Dijkstra + 记忆化搜索 好题)
- HDU 1142 A Walk Through the Forest
- 【Dijkstra+DFS(记忆化)】hdu 1142 A Walk Through the Forest(外:hdu 1428)
- hdu 1142 A Walk Through the Forest(最短路径+dfs)
- HDU 1142 A Walk Through the Forest【记忆化搜索+最短路Dijkstra算法】
- hdu 1142 A Walk Through the Forest
- hdu 1142 A Walk Through the Forest (最短路+dfs)
- hdu 1142 A Walk Through the Forest
- hdu 1142 A Walk Through the Forest
- hdu 1142 A Walk Through the Forest
- Hdu-1142 A Walk Through the Forest