Advertisement
dipBRUR

26

Nov 20th, 2017
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.34 KB | None | 0 0
  1. // Algorithm: Karp’s minimum mean (or average) weight cycle algorithm
  2. // Strongly Connected Component
  3.  
  4. struct NODE {
  5. int v, w;
  6. NODE() {}
  7. NODE(int _, int __) {
  8. v = _;
  9. w = __;
  10. }
  11. };
  12. struct NODE2{
  13. int node, fTime;
  14. friend bool operator<(NODE2 A, NODE2 B) {
  15. return A.fTime > B.fTime;
  16. }
  17. };
  18. vector <NODE> G[MAXN], G_REV[MAXN], graph[MAXN];
  19. bool vis[MAXN];
  20. int timer;
  21. int dis[MAXN];
  22. int finish[MAXN];
  23. void dfs(int u) {
  24. dis[u] = timer++;
  25. for (NODE e : G[u]) {
  26. if (vis[e.v])
  27. continue;
  28. vis[e.v] = 1;
  29. dfs(e.v);
  30. }
  31. finish[u] = timer++;
  32. }
  33. set <int> SCC;
  34. void dfs2(int u) {
  35. SCC.insert(u);
  36. for (NODE e : G_REV[u]) {
  37. if (vis[e.v])
  38. continue;
  39. vis[e.v] = 1;
  40. dfs2(e.v);
  41. }
  42. }
  43. int dp[MAXN][MAXN];
  44. double KARPS() {
  45. int tNode = SCC.size();
  46. int u;
  47. for (auto it : SCC) {
  48. u = it;
  49. break;
  50. }
  51. int here[MAXN] = {0};
  52. for (int n : SCC) {
  53. here[n] = 1;
  54. }
  55. for (int n : SCC) {
  56. for (NODE e : G[n]) {
  57. if (!here[e.v])
  58. continue;
  59. graph[n].push_back(e);
  60. }
  61. }
  62. for (int i = 0; i < MAXN; i++) {
  63. for (int j = 0; j < MAXN; j++) {
  64. dp[i][j] = INF;
  65. }
  66. }
  67. dp[0][u] = 0;
  68.  
  69. for (int k = 1; k <= tNode; k++) { // edge
  70. for (int u : SCC) { // node num
  71. for (NODE e : graph[u]) { // child
  72. if (dp[k - 1][u] != INF) {
  73. int wt = dp[k - 1][u] + e.w;
  74. dp[k][e.v] = min(dp[k][e.v], wt);
  75. }
  76. }
  77. }
  78. }
  79. double mean[MAXN];
  80. for (int i = 0; i < MAXN; i++) {
  81. mean[i] = -1;
  82. }
  83. for (int u : SCC) {
  84. int fCost = dp[tNode][u];
  85. if (fCost == INF)
  86. continue;
  87. for (int k = 0; k < tNode; k++) {
  88. int nowCost = dp[k][u];
  89. if (nowCost != INF && nowCost <= fCost) {
  90. double m = ((double)fCost - nowCost) / (tNode - k);
  91. mean[u] = max(mean[u], m);
  92. }
  93. }
  94. }
  95. double res = INF;
  96. for (int u : SCC) {
  97. if (mean[u] == -1) continue;
  98. res = min(res, mean[u]);
  99. }
  100. return res;
  101. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement