manaranjanfav

Untitled

Sep 23rd, 2017
1,001
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. #define ll long long int
  3. using namespace std;
  4. vector<pair<int,int> > v[100005];
  5. ll sz[100005];
  6. int arr[100005];
  7. ll ans[100005];
  8. void pehle()
  9. {
  10. for(int i=0;i<=100000;i++)
  11. {
  12. arr[i]=i;
  13. sz[i]=1;
  14. }
  15. }
  16. int root(int a)
  17. {
  18. while(arr[a]!=a)
  19. {
  20. arr[a]=arr[arr[a]];
  21. a=arr[a];
  22. }
  23. return a;
  24. }
  25. void join(int a,int b)
  26. {
  27. int x=root(a);
  28. int y=root(b);
  29. if(x!=y)
  30. {
  31. if(sz[x]<sz[y])
  32. {
  33. arr[x]=y;
  34. sz[y]+=sz[x];
  35. }
  36. else
  37. {
  38. arr[y]=x;
  39. sz[x]+=sz[y];
  40. }
  41. }
  42. }
  43. int main()
  44. {
  45. int n,q;
  46. cin>>n>>q;
  47. int x,y,w;
  48. for(int i=0;i<n-1;i++)
  49. {
  50. cin>>x>>y>>w;
  51. for(int j=1;j<=sqrt(w);j++)
  52. {
  53. if(w%j==0)
  54. {
  55. if(w%j==j)
  56. {
  57. v[j].push_back({x,y});
  58. }
  59. else
  60. {
  61. v[j].push_back({x,y});
  62. v[w/j].push_back({x,y});
  63. }
  64. }
  65. }
  66.  
  67. }
  68. pehle();
  69.  
  70. for(int i=1;i<=100000;i++)
  71. {
  72. ll gg=0;
  73. for(auto it : v[i])
  74. {
  75. join(it.first,it.second);
  76. }
  77. for(auto it : v[i])
  78. {
  79. arr[it.first]=it.first;
  80. arr[it.second]=it.second;
  81. int s=sz[it.first];
  82. gg+=(s*(s-1))/2;
  83. int g=sz[it.second];
  84. gg+=(g*(g-1))/2;
  85. sz[it.first]=1;
  86. sz[it.second]=1;
  87.  
  88. }
  89. ans[i]=gg;
  90.  
  91. }
  92. while(q--)
  93. {
  94. int k;
  95. cin>>k;
  96. cout<<ans[k]<<"\n";
  97. }
  98. return 0;
  99. }
Add Comment
Please, Sign In to add comment