Descriptionios
Input算法
Output数组
1 /** 2 *Dijkstra + 静态邻接表 + 优先队列优化 3 */ 4 5 #include <iostream> 6 #include <deque> 7 #include <queue> 8 #include <cstdio> 9 #include <cstring> 10 #include <algorithm> 11 12 using namespace std; 13 14 const int MAXV = 1001; //最大边数 15 const int INF = 0x3f3f3f3f; //最大权值 16 struct Edge 17 { 18 int to; 19 int link; 20 int w; 21 void set_val(int a, int b, int c){to = a, link = b, w = c;} 22 }edge[MAXV * MAXV >> 1]; //存储边 23 int pre[MAXV]; 24 25 struct Node 26 { 27 int v; //顶点的标号 28 int w; //顶点v到源点的最短路 29 Node(int a, int b) {v = a; w = b;} 30 void set_val(int a, int b) {v = a; w = b;} 31 }; //设立该结构体的目的:做为优先队列的结点 32 int d[MAXV]; //记录最短路 33 bool done[MAXV]; //记录是否已找到最短路,避免重复访问 34 int n, m; 35 36 bool operator < (const Node& x, const Node& y) 37 { 38 return x.w < y.w; 39 } 40 41 int main() 42 { 43 int t, ca = 1; 44 scanf("%d", &t); 45 while(t--){ 46 scanf("%d %d", &n, &m); 47 //创建静态邻接表 48 memset(pre, -1, sizeof(pre)); 49 for(int i = 0; m--; ){ 50 int a, b, c; 51 scanf("%d %d %d", &a, &b, &c); 52 edge[i].set_val(a, pre[b], c); 53 pre[b] = i++; 54 edge[i].set_val(b, pre[a], c); 55 pre[a] = i++; 56 } 57 58 //执行Dij算法,使用最小堆进行优化 59 memset(done, false, sizeof(done)); 60 memset(d, 0, sizeof(d)); //d数组的初始化方式是关键! 61 d[1] = INF; 62 priority_queue<Node> que; 63 que.push(Node(1, d[1])); //源点入队 64 done[1] = true; 65 while(!que.empty()){ 66 Node cur = que.top(); 67 que.pop(); 68 for(int i = pre[cur.v]; i != -1; i = edge[i].link){ 69 int to = edge[i].to; 70 if(!done[to] && d[to] < min(cur.w, edge[i].w)){ 71 d[to] = min(cur.w, edge[i].w); 72 que.push(Node(to, d[to])); 73 } 74 } 75 } 76 77 //输出结果 78 printf("Scenario #%d:\n%d\n\n", ca++, d[n]); 79 } 80 return 0; 81 }