Source code for submission s574

fr.cpp

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. typedef struct EDGE
  6. {
  7. int u;
  8. int v;
  9. int w;
  10. }
  11. EDGE;
  12.  
  13. typedef struct FOL
  14. {
  15. int v;
  16. int w;
  17. }
  18. FOL;
  19.  
  20. EDGE Input[4000];
  21.  
  22. int Degree[4000];
  23. FOL Fol[4000];
  24. int iFol[4000];
  25. int CurIndex[4000];
  26.  
  27. int Pred[4000];
  28. int Q[4000];
  29. int QBeg, QEnd;
  30.  
  31. int wPred[4000];
  32. int Cost[4000];
  33.  
  34. int MyMin(int a, int b)
  35. {
  36. return (a < b) ? a : b;
  37. }
  38.  
  39. int main()
  40. {
  41. int n, c;
  42. while(scanf("%d%d", &n, &c) > 0)
  43. {
  44. c--;
  45.  
  46. memset(Degree, 0, sizeof(Degree));
  47. memset(CurIndex, 0, sizeof(CurIndex));
  48. memset(Cost, 0, sizeof(Cost));
  49.  
  50. int m = n - 1;
  51. for(int i = 0; i < m; i++)
  52. {
  53. scanf("%d%d%d", &(Input[i].u), &(Input[i].v), &(Input[i].w));
  54. Input[i].u--;
  55. Input[i].v--;
  56.  
  57. Input[i + m].u = Input[i].v;
  58. Input[i + m].v = Input[i].u;
  59. Input[i + m].w = Input[i].w;
  60.  
  61. Degree[Input[i].u]++;
  62. Degree[Input[i].v]++;
  63. }
  64.  
  65. iFol[0] = 0;
  66. for(int i = 0; i < n; i++)
  67. {
  68. iFol[i + 1] = iFol[i] + Degree[i];
  69. }
  70.  
  71. int mm = m * 2;
  72. for(int i = 0; i < mm; i++)
  73. {
  74. int e = Input[i].u;
  75. Fol[iFol[e] + CurIndex[e]++] = (FOL) {Input[i].v, Input[i].w};
  76. }
  77. //seznam nasledniku hotov
  78.  
  79. /*for(int i = 0; i < mm; i++)
  80. {
  81. printf("%d->%d with %d\n", Input[i].u + 1, Input[i].v + 1, Input[i].w);
  82. }*/
  83.  
  84. Pred[c] = -1;
  85. QBeg = 0;
  86. QEnd = 0;
  87.  
  88. Q[QEnd++] = c;
  89. while(QBeg < QEnd)
  90. {
  91. int cur = Q[QBeg++];
  92. for(int i = iFol[cur]; i < iFol[cur + 1]; i++)
  93. {
  94. int t = Fol[i].v;
  95. if(t == Pred[cur])
  96. {
  97. continue;
  98. }
  99.  
  100. Pred[t] = cur;
  101. wPred[t] = Fol[i].w;
  102. Q[QEnd++] = t;
  103. }
  104. }
  105. //Pred inicializovan
  106.  
  107. QBeg = 0;
  108. QEnd = 0;
  109.  
  110. for(int i = 0; i < n; i++)
  111. {
  112. if((i != c) && (Degree[i] == 1))
  113. {
  114. Q[QEnd++] = i;
  115. Cost[i] = 1 << 30;
  116. }
  117. }
  118.  
  119. while(QBeg < QEnd)
  120. {
  121. int cur = Q[QBeg++];
  122. int pred = Pred[cur];
  123.  
  124. Cost[pred] += MyMin(Cost[cur], wPred[cur]);
  125. //printf("Cost of %d increased by min(%d, %d)\n", pred + 1, Cost[cur], wPred[cur]);
  126.  
  127. if(pred != c)
  128. {
  129. if(--Degree[pred] == 1)
  130. {
  131. Q[QEnd++] = pred;
  132. }
  133. }
  134. }
  135. //Cost inicializovan
  136.  
  137. printf("%d\n", Cost[c]);
  138. }
  139.  
  140. return 0;
  141. }
  142.