记录编号 344676 评测结果 AAAAAAAAAAAAAAAAAAAA
题目名称 [NOI 2011]道路修建 最终得分 100
用户昵称 GravatarAntiLeaf 是否通过 通过
代码语言 C++ 运行时间 4.598 s
提交时间 2016-11-10 14:48:43 内存使用 38.44 MiB
显示代码纯文本
  1. #include<cstdio>
  2. #include<cstring>
  3. #include<algorithm>
  4. using namespace std;
  5. const int maxn=1000010;
  6. namespace mine{
  7. //#define NEGATE_NEEDED
  8. template<class T>inline void readint(T &__x){
  9. static int __c;
  10. #ifdef NEGATE_NEEDED
  11. static bool __neg;
  12. #endif
  13. __x=0;
  14. #ifdef NEGATE_NEEDED
  15. __neg=false;
  16. #endif
  17. do __c=getchar();while(__c==' '||__c=='\n'||__c=='\r'||__c=='\t');
  18. #ifdef NEGATE_NEEDED
  19. if(__c=='-'){
  20. __neg=true;
  21. __c=getchar();
  22. }
  23. #endif
  24. for(;__c>='0'&&__c<='9';__c=getchar())__x=__x*10+(__c^48);
  25. #ifdef NEGATE_NEEDED
  26. if(__neg)__x=-__x;
  27. #endif
  28. }
  29. template<class T>inline void writeint(T __x){
  30. static int __a[40],__i,__j;
  31. #ifdef NEGATE_NEEDED
  32. static bool __neg;
  33. __neg=__x<0;
  34. if(__neg)__x=-__x;
  35. #endif
  36. __i=0;
  37. do{
  38. __a[__i++]=__x%10^48;
  39. __x/=10;
  40. }while(__x);
  41. #ifdef NEGATE_NEEDED
  42. if(__neg)putchar('-');
  43. #endif
  44. for(__j=__i-1;__j^-1;__j--)putchar(__a[__j]);
  45. }
  46. }
  47. using namespace mine;
  48. struct edge{int to,prev,w;}e[maxn<<1];
  49. void addedge(int,int,int);
  50. void bfs();
  51. int n,last[maxn],len=0,prt[maxn],size[maxn],q[maxn],head,tail,x,y,z;
  52. long long ans=0ll;
  53. int main(){
  54. #define MINE
  55. #ifdef MINE
  56. freopen("noi2011_road.in","r",stdin);
  57. freopen("noi2011_road.out","w",stdout);
  58. #endif
  59. readint(n);
  60. for(int i=1;i<n;i++){
  61. readint(x);
  62. readint(y);
  63. readint(z);
  64. addedge(x,y,z);
  65. addedge(y,x,z);
  66. }
  67. bfs();
  68. writeint(ans);
  69. #ifndef MINE
  70. printf("\n-------------------------DONE-------------------------\n");
  71. for(;;);
  72. #else
  73. fclose(stdin);
  74. fclose(stdout);
  75. #endif
  76. return 0;
  77. }
  78. inline void addedge(int x,int y,int z){
  79. e[++len].to=y;
  80. e[len].w=z;
  81. e[len].prev=last[x];
  82. last[x]=len;
  83. }
  84. void bfs(){
  85. int x;
  86. head=tail=1;
  87. q[tail++]=1;
  88. while(head!=tail){
  89. x=q[head++];
  90. size[x]=1;
  91. for(int i=last[x];i;i=e[i].prev)if(e[i].to!=prt[x]){
  92. prt[e[i].to]=x;
  93. q[tail++]=e[i].to;
  94. }
  95. }
  96. for(int i=n;i;i--){
  97. size[prt[q[i]]]+=size[q[i]];
  98. }
  99. for(int k=1;k<=n;k++)
  100. for(int i=last[q[k]];i;i=e[i].prev)if(e[i].to!=prt[q[k]])ans+=e[i].w*(long long)abs(n-(size[e[i].to]<<1));
  101. }
  102. /*
  103. 6
  104. 1 2 1
  105. 1 3 1
  106. 1 4 2
  107. 6 3 1
  108. 5 2 1
  109. Answer:
  110. 20
  111. */