Calculate the Kth shortest path in a Directed Acyclic Graph(DAG). Although there exists a complicated way to calculate the Kth shortest Path in Arbitrary Graph, we can get the answer using DP by taking advantage of the property of DAG. A DP way is available because the DAG naturally has got an order which we use frequently.
We just maintain an array of size K for each node, representing first K shortest path from source to that node. When we computing a node I, we just consider all the nodes that leads an edge to I. All we need to do is merging the arrays to get the first K items, then we fill them in the array of Node I.
Note: there may be multiple edges between two nodes.
Here is the code:
- #include <iostream>
- using namespace std;
- const int N = 1001;
- int ad[N][N], len[N][N], d[N][110];
- int pt[N];
- int n, m, kth;
- int main()
- {
- int i, j, k, t;
- freopen("cowjog.in", "r", stdin);
- freopen("cowjog.out", "w", stdout);
- scanf("%d%d%d",&n, &m, &kth);
- for(; m; m--)
- {
- scanf("%d%d%d",&i, &j, &k);
- ad[j][++ad[j][0]] = i;
- len[j][ad[j][0]] = k;
- }
- memset(d, -1, sizeof(d));
- d[n][0] = 0;
- for(i = n - 1; i >= 1; i--)
- {
- memset(pt, 0, sizeof(pt));
- for(int cnt = 0; cnt < kth; cnt++)
- {
- int tmp = -1, minD = INT_MAX;
- for(j = 1; j <= ad[i][0]; j++)
- {
- k = ad[i][j], t = len[i][j];
- if(d[k][pt[j]] != -1 && t + d[k][pt[j]] < minD)
- {
- minD = t + d[k][pt[j]];
- tmp = j;
- }
- }
- if(minD != INT_MAX)
- {
- d[i][cnt] = minD;
- pt[tmp]++;
- }
- }
- }
- for(i = 0; i < kth; i++)
- printf("%d/n",d[1][i]);
- scanf("%d",&n);
- return 0;
- }