1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| #include <cstdio> #include <iostream> #include <algorithm> #include <queue> #include <cstring> using namespace std;
const int INF = 0x3f3f3f3f; const int MAXnumNode = 110; const int MAXnumEdge = 20000;
int numNode, numEdge; int head[MAXnumNode]; int dis[MAXnumNode]; bool vis[MAXnumNode]; int output[MAXnumNode];
struct Edge{ int to; int cost; int next; }edge[MAXnumEdge];
void init() { memset(vis, false, sizeof(vis)); memset(dis, INF, sizeof(dis)); memset(head, -1, sizeof(head)); memset(output, 0, sizeof(output)); }
bool SPFA(int start) { queue<int > que; que.push(start); vis[start] = true; dis[start] = 0;
while(!que.empty()){ int top = que.front(); que.pop(); vis[top] = false; output[top]++; if(output[top] > numNode) return false; for(int k = head[top]; ~k; k = edge[k].next){ if(dis[edge[k].to] > dis[top] + edge[k].cost){ dis[edge[k].to] = dis[top] + edge[k].cost; if(!vis[edge[k].to]){ vis[edge[k].to] = true; que.push(edge[k].to); } } } } return true; }
int main() { while(scanf("%d%d", &numNode, &numEdge) && (numEdge || numNode)){ int from, to, cost; init(); for(int i = 1; i <= numEdge * 2; i++){ scanf("%d%d%d", &from, &to, &cost); edge[i].to = to; edge[i].cost = cost; edge[i].next = head[from]; head[from] = i;
i++; edge[i].to = from; edge[i].cost = cost; edge[i].next = head[to]; head[to] = i; } int start = 1; if(SPFA(start)) printf("%d\n", dis[numNode]); } return 0; }
|