-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmean-weight-cycle-of-a-graph.cpp
101 lines (84 loc) · 2.22 KB
/
mean-weight-cycle-of-a-graph.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/**
* @file mean-weight-cycle-of-a-graph.cpp
* @author prakash (prakashsellathurai@gmail.com)
* @brief
You are given a weighted directed graph G with n vertices and m edges. The
mean weight of a cycle is the sum of its edge weights divided by the number of
its edges. Find a cycle in G of minimum mean weight.
* @version 0.1
* @date 2021-08-08
*
* @copyright Copyright (c) 2021
*
*/
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
const int V = 4;
// a struct to represent edges
struct edge {
int from, weight;
};
// vector to store edges
vector<edge> edges[V];
void addedge(int u, int v, int w) { edges[v].push_back({u, w}); }
// calculates the shortest path
void shortestpath(int dp[][V]) {
// initializing all distances as -1
for (int i = 0; i <= V; i++)
for (int j = 0; j < V; j++)
dp[i][j] = -1;
// shortest distance from first vertex
// to in tself consisting of 0 edges
dp[0][0] = 0;
// filling up the dp table
for (int i = 1; i <= V; i++) {
for (int j = 0; j < V; j++) {
for (int k = 0; k < edges[j].size(); k++) {
if (dp[i - 1][edges[j][k].from] != -1) {
int curr_wt = dp[i - 1][edges[j][k].from] + edges[j][k].weight;
if (dp[i][j] == -1)
dp[i][j] = curr_wt;
else
dp[i][j] = min(dp[i][j], curr_wt);
}
}
}
}
}
// Returns minimum value of average weight of a
// cycle in graph.
double minAvgWeight() {
int dp[V + 1][V];
shortestpath(dp);
// array to store the avg values
double avg[V];
for (int i = 0; i < V; i++)
avg[i] = -1;
// Compute average values for all vertices using
// weights of shortest paths store in dp.
for (int i = 0; i < V; i++) {
if (dp[V][i] != -1) {
for (int j = 0; j < V; j++)
if (dp[j][i] != -1)
avg[i] = max(avg[i], ((double)dp[V][i] - dp[j][i]) / (V - j));
}
}
// Find minimum value in avg[]
double result = avg[0];
for (int i = 0; i < V; i++)
if (avg[i] != -1 && avg[i] < result)
result = avg[i];
return result;
}
int main() {
addedge(0, 1, 1);
addedge(0, 2, 10);
addedge(1, 2, 3);
addedge(2, 3, 2);
addedge(3, 1, 0);
addedge(3, 0, 8);
cout << minAvgWeight();
return 0;
}