URAL 1434 Buses in Vasyuki (双静态邻接链表+BFS)
2015-09-12 22:07
423 查看
#include<stdio.h> #define MAX_ROUTES 1000 #define MAX_STOPS 100000 #define MAX_NODES 200000 typedef struct StopInRoute{ int stop; int next; }StopInRoute; StopInRoute stopArray[MAX_NODES + 1];//used as adjacent list int routeHead[MAX_ROUTES + 1]; int stopNum; typedef struct RouteByStop{ int route; int next; }RouteByStop; RouteByStop routeArray[MAX_NODES + 1];//used as adjacent list int stopHead[MAX_STOPS + 1]; int routeNum; int queue[MAX_STOPS + 1]; int head; int tail; int father[MAX_STOPS + 1]; int routeVisited[MAX_ROUTES + 1]; int stack[MAX_STOPS+1]; int top; int main(){ int numOfRoutes, numOfStops; scanf("%d %d", &numOfRoutes, &numOfStops); int indexOfRoute, indexOfStop; for (indexOfRoute = 1; indexOfRoute <= numOfRoutes; indexOfRoute++){ int numOfStopsInTheRoute; scanf("%d", &numOfStopsInTheRoute); for (indexOfStop = 1; indexOfStop <= numOfStopsInTheRoute; indexOfStop++){ int stop; scanf("%d", &stop); stopNum++; stopArray[stopNum].stop = stop; stopArray[stopNum].next = routeHead[indexOfRoute]; routeHead[indexOfRoute] = stopNum; routeNum++; routeArray[routeNum].route = indexOfRoute; routeArray[routeNum].next = stopHead[stop]; stopHead[stop] = routeNum; } } int startStop, endStop; scanf("%d %d", &startStop, &endStop); queue[tail++] = startStop; father[startStop] = -1; while (head < tail){ int stopPoped = queue[head++]; for (indexOfRoute = stopHead[stopPoped]; indexOfRoute != 0; indexOfRoute = routeArray[indexOfRoute].next){ int route = routeArray[indexOfRoute].route; if (routeVisited[route] == 1) continue; routeVisited[route] = 1; for (indexOfStop = routeHead[route]; indexOfStop != 0; indexOfStop = stopArray[indexOfStop].next){ int stop = stopArray[indexOfStop].stop; if (father[stop] != 0) continue; if (stop == endStop){ stack[top++] = endStop; stack[top++] = stopPoped; stop = stopPoped; while (father[stop] != -1){ stack[top] = father[stop]; top++; stop = father[stop]; } int minMoney = top - 1; printf("%d\n", minMoney); for (top--; top >= 0; top--) printf("%d%c", stack[top], top == 0 ? '\n' : ' '); return 0; } father[stop] = stopPoped; int stopPushed = stop; queue[tail++] = stopPushed; }//end fo for indexOfStop }//end of for indexOfRoute }//end of while (head < tail) printf("-1"); return 0; }
相关文章推荐
- 初学图论-Kahn拓扑排序算法(Kahn's Topological Sort Algorithm)
- 初学图论-Bellman-Ford单源最短路径算法
- 初学图论-DAG单源最短路径算法
- 初学图论-Dijkstra单源最短路径算法
- Ural 1910. Titan Ruins: Hidden Entrance
- Surrounded Regions
- Word Ladder, Gray Code
- UVA 11624
- HDU1495
- HDU2612 Find a way
- HDU1241 Oil Deposits
- Hdu2444二分图
- 最少步数BFS
- 转v_JULY_v的 BFS和DFS优先搜索算法
- 2015 寒假搜索专题 I - Meteor Shower(BFS)
- Same Tree
- E - Roads in the North
- DFS&BFS算法总结(1)
- Word Ladder I
- 图的BFS和DFS学习笔记