Source code for submission s914

fr.cpp

  1. #include <iostream>
  2. #include <stdlib.h>
  3. using namespace std;
  4.  
  5. int *connections;
  6. int *efforts;
  7. int nconnections[1000];
  8. int nnodes;
  9. int central;
  10.  
  11. #define pos(a,b) ((a)*1000+(b))
  12. #define min(a,b) ((a)<(b)?(a):(b))
  13.  
  14. #define DEBUG
  15.  
  16. int calculate(int me, int sourcenode) {
  17. int p;
  18. int ret=0;
  19. int indiv;
  20. int target;
  21.  
  22. // go through all pipes
  23. for(p=0;p<nconnections[me];p++) {
  24. // get ID of the target node
  25. target=connections[pos(me,p)];
  26.  
  27. //is this the source pipe?
  28. if(target==sourcenode) continue;
  29.  
  30. //is this a pipe with minimal effort?
  31. if(efforts[pos(me,p)]==1) {
  32. // then there's no need to calculate the rest of this sub-tree
  33. ret += 1;
  34. continue;
  35. }
  36.  
  37. //is this a pipe with a rose-head?
  38. if(nconnections[target]==1) {
  39. ret += efforts[pos(me,p)];
  40. continue;
  41. }
  42.  
  43. //... so it's a regular pipe
  44. indiv=calculate(target,me);
  45. ret+= min(efforts[pos(me,p)],indiv);
  46. }
  47. return ret;
  48. }
  49.  
  50. int main() {
  51. int i;
  52. int a,b,c,w;
  53.  
  54. connections=(int*)malloc(1000*1000*sizeof(int));
  55. efforts=(int*)malloc(1000*1000*sizeof(int));
  56. while(cin >> nnodes >> central) {
  57. // init
  58. central--;
  59. for(i=0;i<nnodes;i++) {
  60. nconnections[i]=0;
  61. }
  62.  
  63. // build graph
  64. for(i=1;i<nnodes;i++) {
  65. cin >> a >> b >> w;
  66. a--;
  67. b--;
  68. c=nconnections[a]++;
  69. connections[pos(a,c)]=b;
  70. efforts[pos(a,c)]=w;
  71. c=nconnections[b]++;
  72. connections[pos(b,c)]=a;
  73. efforts[pos(b,c)]=w;
  74. }
  75.  
  76. cout << calculate(central,-1) << endl;
  77. }
  78. free(connections);
  79. free(efforts);
  80. return 0;
  81. }
  82.