写一个这么简单的dijkstra算法居然找bug找了了几个小时。在寻找未入集合的“最小”节点时,漏了最后全部入集合找不到的情况,导致最后队列无法结束,造成runtime error。但是很奇怪,在自己的dev-cpp中测试运行却没事,但调试时就出现了这个死循环,难道软件执行到一定次数会自动跳出?
另外,由于OJ中并没有提供测试数据(除了samle),很难知道自己错在哪,刚才用了一点小手段,在可能出现错误的地方加一个
while(1);
这样,如果在这之前程序没有RE,那OJ显示错误必是Time limited Exceeded,作用好比一个断点。
最后保存一下代码,用的是比较“通用”的领接表方式写的,虽然本可以更简单。
#include<stdio.h>
#include<stdlib.h>
#define max 1005
const int INF = 0x3f3f3f3f;
struct Edge{
int PrtNode;
int weight;
Edge *next;
};
struct Node{
Edge *firstEdge;
};
struct Graph{
int VN;
int EN;
Node **Map;
};
int visited[max];
long dis[max];
Graph *InsertEdge(Graph *G){
int e1, e2, weight;
Edge *tmp;
for(int i=0;i<G->EN;i++){
scanf("%d%d%d", &e1, &e2, &weight);
tmp = G->Map[e1-1]->firstEdge;
while(tmp && tmp->PrtNode != e2-1)
tmp = tmp->next;
if(tmp){
if(tmp->weight <= weight)
continue;
else{
tmp->weight = weight;
tmp = G->Map[e2-1]->firstEdge;
while(tmp && tmp->PrtNode != e1-1)
tmp = tmp->next;
tmp->weight = weight;
continue;
}
}
tmp = (Edge *)malloc(sizeof(Edge));
tmp->weight = weight;
tmp->PrtNode = e2-1;
tmp->next = G->Map[e1-1]->firstEdge;
G->Map[e1-1]->firstEdge = tmp;
tmp = (Edge *)malloc(sizeof(Edge));
tmp->weight = weight;
tmp->PrtNode = e1-1;
tmp->next = G->Map[e2-1]->firstEdge;
G->Map[e2-1]->firstEdge = tmp;
}
return G;
}
Graph *CreatMap(Graph *G){
G = (Graph *)malloc(sizeof(Graph));
scanf("%d%d", &G->EN, &G->VN);
G->Map = (Node **)malloc(sizeof(Node *) * G->VN);
for(int i=0;i<G->VN;i++){
G->Map[i] = (Node *)malloc(sizeof(Node));
G->Map[i]->firstEdge = (Edge *)malloc(sizeof(Edge));
G->Map[i]->firstEdge = NULL;
}
G = InsertEdge(G);
return G;
}
int FindMin(Graph *G){
int min = G->VN - 1;
int M = INF;
for(int i=0;i<G->VN;i++){
if( !visited[i] && dis[i] < M){
min = i;
M = dis[i];
}
}
return min;
}
void Dijkstra(Graph *G){
for(int i=0;i<G->VN;i++){
visited[i] = 0;
dis[i] = INF;
}
int queue[max], hd = 0, tl = 0, st;
Edge *tmp;
queue[tl++] = G->VN - 1;
dis[G->VN - 1] = 0;
while(hd < tl){
st = queue[hd++];
visited[st] = 1;
tmp = G->Map[st]->firstEdge;
while(tmp){
if(dis[tmp->PrtNode] > dis[st] + tmp->weight)
dis[tmp->PrtNode] = dis[st] + tmp->weight;
tmp = tmp->next;
}
st = FindMin(G);
if(st != G->VN - 1)
queue[tl++] = st;
}
}
int main(){
Graph *G;
G = CreatMap(G);
Dijkstra(G);
printf("%ld", dis[0]);
return 0;
}