[关闭]
@Junlier 2018-08-21T09:15:05.000000Z 字数 1757 阅读 1676

P3806 【模板】点分治1(题解)(点分治)

图论——点分治
洛谷题目传送门

  1. #include<iostream>
  2. #include<cstdlib>
  3. #include<cstdio>
  4. #include<cmath>
  5. #include<cstring>
  6. #include<iomanip>
  7. #include<algorithm>
  8. #include<ctime>
  9. #include<queue>
  10. #include<stack>
  11. #include<vector>
  12. #define rg register
  13. #define il inline
  14. #define lst long long
  15. #define ldb long double
  16. #define N 10050
  17. #define KK 10000050
  18. using namespace std;
  19. const int Inf=1e9;
  20. int n,m,K,cnt,top;
  21. int root,Max,tot;
  22. struct EDGE{
  23. int to,nxt,v;
  24. }ljl[N<<1];
  25. int hd[N],ans;
  26. int siz[N],vis[N];
  27. int pot[KK],Q[N],dis[N];
  28. il int read()
  29. {
  30. rg int s=0,m=0;rg char ch=getchar();
  31. while(ch<'0'||ch>'9'){if(ch=='-')m=1;ch=getchar();}
  32. while(ch>='0'&&ch<='9')s=(s<<3)+(s<<1)+(ch^48),ch=getchar();
  33. return m?-s:s;
  34. }
  35. il void add(rg int p,rg int q,rg int o)
  36. {
  37. ljl[++cnt]=(EDGE){q,hd[p],o};hd[p]=cnt;
  38. }
  39. void get_root(rg int now,rg int fm)
  40. {
  41. siz[now]=1;rg int num=0;
  42. for(rg int i=hd[now];i;i=ljl[i].nxt)
  43. {
  44. rg int qw=ljl[i].to;
  45. if(qw==fm||vis[qw])continue;
  46. get_root(qw,now);
  47. siz[now]+=siz[qw];
  48. num=max(num,siz[qw]);
  49. }
  50. num=max(num,tot-siz[now]);
  51. if(Max>num)Max=num,root=now;
  52. }
  53. void get_dis(rg int now,rg int fm)
  54. {
  55. Q[++top]=dis[now];
  56. for(rg int i=hd[now];i;i=ljl[i].nxt)
  57. {
  58. rg int qw=ljl[i].to;
  59. if(qw==fm||vis[qw])continue;
  60. dis[qw]=dis[now]+ljl[i].v;
  61. get_dis(qw,now);
  62. }
  63. }
  64. il void Query(rg int now,rg int base,rg int op)
  65. {
  66. dis[now]=base,top=0;
  67. get_dis(now,0);
  68. for(rg int i=1;i<=top;++i)
  69. for(rg int j=i+1;j<=top;++j)
  70. pot[Q[i]+Q[j]]+=op;
  71. }
  72. void divide(rg int now)
  73. {
  74. Query(now,0,1),vis[now]=1;
  75. rg int all=tot;
  76. for(rg int i=hd[now];i;i=ljl[i].nxt)
  77. {
  78. rg int qw=ljl[i].to;
  79. if(vis[qw])continue;
  80. Query(qw,ljl[i].v,-1);
  81. tot=siz[now]>siz[qw]?siz[qw]:all-siz[now];
  82. Max=Inf,root=0;
  83. get_root(qw,0),divide(root);
  84. }
  85. }
  86. int main()
  87. {
  88. n=read(),m=read();
  89. for(rg int i=1;i<n;++i)
  90. {
  91. rg int p=read(),q=read(),o=read();
  92. add(p,q,o),add(q,p,o);
  93. }
  94. tot=n,Max=Inf;
  95. get_root(1,0);divide(root);
  96. // puts("YES");
  97. for(rg int i=1;i<=m;++i)
  98. {
  99. K=read();
  100. if(pot[K])puts("AYE");
  101. else puts("NAY");
  102. }
  103. return 0;
  104. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注