Witam,
Mam pewien problem z zadaniem. Otóż polega on na znalezieniu w danym grafie najkrótszej ścieżki pomiędzy źródłem (source w kodzie), a wierzchołkiem docelowym (target).
Posiadałem już wcześniej algorytm Dijkstry, który nieco zmodyfikowałem do tego zadania. Jednak problem polega na tym, że zwraca minimalnie złą odpowiedź. Dla danych wejściowych:
8 15
1 2 5
1 3 4
2 3 2
2 3 5
2 6 5
3 5 3
3 4 4
3 6 6
4 6 5
4 7 5
4 8 4
5 6 4
5 7 7
6 7 5
7 8 4
2
1 7
2 2
Poprawne wyjścia to:
13
0
Mój program, jednak daje odpowiedzi: 12 i 0. Nie mam pojęcia skąd ten błąd w pierwszej, wydaje mi się, że wszystko jest prawidłowo zrobione.
Jeśli ktoś byłby uprzejmy i rzucił okiem na mój kod, będę wdzięczny :).
#include<queue>
#include<cstdio>
#include<vector>
#include<math.h>
using namespace std;
#define MAXINT (int)(pow(2,31)-1)
#define MAXV 10000
int G[MAXV][MAXV];
int total;
int dist[MAXV];
int parent[MAXV];
bool visited[MAXV];
void dijkstra(int s)
{
priority_queue<pair<int,int> >Q;
pair<int,int>nodes;
int i,j;
for (int i=0; i<total;++i) {
dist[i]=MAXINT;
parent[i]=-1;
visited[i]=false;
}
dist[s]=0;
Q.push(pair<int,int>(dist[s], s));
while(!Q.empty()) {
nodes=Q.top();
Q.pop();
i=nodes.second;
if(!visited[i]) {
visited[i]=true;
for (j=0;j<total;++j)
if(!visited[j] && G[i][j]>0 && dist[i]+G[i][j]<dist[j]) {
dist[j]=dist[i]+G[i][j];
parent[j]=i;
Q.push(pair<int,int>(-dist[j],j));
}
}
}
}
void findPath(int end,int c) {
int weight=0;
while (parent[end]!=-1) {
weight+=c;
end=parent[end];
}
printf("%d\n",weight);
}
int main()
{
int a, b, c,il,source,target;
int m;
scanf("%d %d",&total, &m);
for (int i=0;i<m;++i) {
scanf("%d %d %d",&a, &b, &c);
G[a][b]=c;
}
scanf("%d",&il);
for(int i=0;i<il;++i){
scanf("%d %d",&source, &target);
dijkstra(source);
findPath(target,c);
}
return 0;
}