Source code for submission s608

three.cpp

  1. #include <algorithm>
  2. #include <cctype>
  3. #include <cmath>
  4. #include <cstdio>
  5. #include <cstring>
  6. #include <iostream>
  7. #include <list>
  8. #include <map>
  9. #include <queue>
  10. #include <set>
  11. #include <sstream>
  12. #include <stack>
  13. #include <string>
  14. #include <utility>
  15. #include <vector>
  16. using namespace std;
  17.  
  18. #define DEBUG(x) cerr << ">> " << #x << ": " << x << endl;
  19. #define REP(i,a) for (int i =0; i < (a);++i)
  20. #define FOR(i,a,b) for (int i = (a); i <= (b); ++i)
  21.  
  22. struct Edge
  23. {
  24. int target;
  25. int power;
  26. Edge(int to, int por)
  27. {
  28. target = to;
  29. power = por;
  30. }
  31. };
  32.  
  33. struct Node
  34. {
  35. vector<Edge> edges;
  36. };
  37.  
  38. Node* nodes;
  39.  
  40. int root, nodeCount;
  41.  
  42. int getpower(int node, int parent, int selfpower)
  43. {
  44. int sumOfSons = 0;
  45. if (nodes[node].edges.size() == 1 && node != root-1)
  46. {
  47. return selfpower;
  48. }
  49. for (vector<Edge>::iterator it = nodes[node].edges.begin(); it != nodes[node].edges.end(); ++it)
  50. {
  51. if (it->target == parent) continue;
  52. int fromSon = getpower(it->target, node, it->power);
  53. sumOfSons += fromSon;
  54. }
  55. if (node == root-1) { return sumOfSons; }
  56. else
  57. { if (sumOfSons < selfpower) { return sumOfSons; } else { return selfpower; } }
  58. }
  59.  
  60.  
  61. int main() {
  62. while (scanf("%d%d", &nodeCount, &root) != EOF)
  63. {
  64. nodes = new Node[nodeCount];
  65. for (int i = 0; i < nodeCount-1;i++)
  66. {
  67. int from, to, epower;
  68. scanf("%d%d%d",&from, &to, &epower);
  69. nodes[from-1].edges.push_back(Edge(to-1, epower));
  70. nodes[to-1].edges.push_back(Edge(from-1, epower));
  71. }
  72. printf("%d\n", getpower(root-1, -1, -1));
  73.  
  74. delete[] nodes;
  75. }
  76. return 0;
  77. }