void QueryWindow::dijkstra_heap(Lgraph Graph,int s,int stime,pre *prenum,int flag) { /*堆优化Dijikstra*/ //int day = 0; int top = 0; heap node; node.dis = stime;//将起始点即编号为s的点的到达时间设为stime node.ver = s;//起始点编号为s //初始化状态数组和最小距离数组和(前驱节点和航班/列次)数组 for(int i = 0; i < Graph->Nv; i ++ ) { st[i] = false; dist[i] = INF; prenum[i].name = QString(); prenum[i].prepoint = -1; if(flag == 1 && !Graph->f_G[i].canFly) st[i] = true; } dist[s] = stime;//初始化起点的时间 push(h,top,node);//将起点入堆 while(top){ auto x = pop(h,top);//取出堆顶元素 int ver = x.ver; if(st[ver]) continue;//如果已经被选中就不再选了 st[ver] = true;//不然就选它 AdjVNode i = new adjVNode; int distance = 0; if(flag == 1){//飞机还是火车 //添加等待时间 distance = x.dis + wait_time; if(ver == s) distance -= wait_time; i = Graph->f_G[ver].First;//确定初边 }else{ distance = x.dis + wait_time2; if(ver == s) distance -= wait_time2; i = Graph->t_G[ver].First; } for( ; i ; i = i->next) { int j = i->adjv; int current_time = distance % 24;//现在的时间对应几点 int wait = (i->weight.go - current_time + 24) % 24;//如果选择这个航班/火车,需要等待的时间 if(dist[j] > distance + wait + i->weight.time) { dist[j] = distance + wait + i->weight.time; node.dis = dist[j]; node.ver = j; prenum[j].prepoint = ver; prenum[j].name = i->weight.name; push(h,top,node);//会重复入堆,还可以优化 } } } }转化成伪代码
时间: 2024-02-14 19:06:39 浏览: 71
以下是伪代码 C 版本的堆优化 Dijkstra 算法:
```
void dijkstra_heap(Lgraph Graph, int s, int stime, pre *prenum, int flag) {
// 初始化状态数组和最小距离数组和(前驱节点和航班/列次)数组
for (int i = 0; i < Graph->Nv; i++) {
st[i] = false;
dist[i] = INF;
prenum[i].name = QString();
prenum[i].prepoint = -1;
if (flag == 1 && !Graph->f_G[i].canFly)
st[i] = true;
}
dist[s] = stime; // 初始化起点的时间
heap h;
int top = 0;
heap node;
node.dis = stime;
node.ver = s;
push(h, top, node); // 将起点入堆
while (top) {
auto x = pop(h, top); // 取出堆顶元素
int ver = x.ver;
if (st[ver]) continue; // 如果已经被选中就不再选了
st[ver] = true; // 不然就选它
AdjVNode i = new adjVNode;
int distance = 0;
if (flag == 1) { // 飞机还是火车
// 添加等待时间
distance = x.dis + wait_time;
if (ver == s) distance -= wait_time;
i = Graph->f_G[ver].First; // 确定初边
} else {
distance = x.dis + wait_time2;
if (ver == s) distance -= wait_time2;
i = Graph->t_G[ver].First;
}
for (; i; i = i->next) {
int j = i->adjv;
int current_time = distance % 24; // 现在的时间对应几点
int wait = (i->weight.go - current_time + 24) % 24; // 如果选择这个航班/火车,需要等待的时间
if (dist[j] > distance + wait + i->weight.time) {
dist[j] = distance + wait + i->weight.time;
node.dis = dist[j];
node.ver = j;
prenum[j].prepoint = ver;
prenum[j].name = i->weight.name;
push(h, top, node); // 会重复入堆,还可以优化
}
}
}
}
```
阅读全文