Advertisement
Guest User

Untitled

a guest
Oct 18th, 2019
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. #include <cstdio>
  2. #include <cstring>
  3. #include <cmath>
  4. #include <algorithm>
  5. #include <vector>
  6. #include <string>
  7. #include <map>
  8. #include <set>
  9. #include <cassert>
  10. using namespace std;
  11. #define rep(i,a,n) for (int i=a;i<n;i++)
  12. #define per(i,a,n) for (int i=n-1;i>=a;i--)
  13. #define pb push_back
  14. #define mp make_pair
  15. #define all(x) (x).begin(),(x).end()
  16. #define fi first
  17. #define se second
  18. #define SZ(x) ((int)(x).size())
  19. typedef vector<int> VI;
  20. typedef long long ll;
  21. typedef pair<int,int> PII;
  22. const ll mod=1000000007;
  23. ll powmod(ll a,ll b) {ll res=1;a%=mod; assert(b>=0); for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;}
  24. // head
  25.  
  26. const int N=40100;
  27. int T,p[N],c[N],dep[N],ch[N],vis[N],st[N],q,ret[N],cp[N];
  28. int n,u,v;
  29. char s[10];
  30.  
  31. vector<PII> e[N],Q[N];
  32. void dfs(int u,int f) {
  33. for (auto v:e[u]) if (v.fi!=f) {
  34. dfs(v.fi,u); p[v.fi]=u; c[v.fi]=v.se;
  35. }
  36. }
  37. int gao(int u,int v) {
  38. T++;
  39. int r=v,tot=0; dep[v]=n;
  40. int ret=-1;
  41. while (r!=u) {
  42. ch[dep[r]]=c[r];
  43. vis[r]=T;
  44. cp[r]=1;
  45. dep[p[r]]=dep[r]-1;
  46. r=p[r];
  47. ret++;
  48. }
  49. vis[u]=T; cp[u]=1;
  50. rep(j,1,n+1) if (vis[j]!=T) {
  51. int top=0,r=j;
  52. while (vis[r]!=T) st[top++]=r,r=p[r];
  53. per(i,0,top) {
  54. int r=st[i];
  55. dep[r]=dep[p[r]]+1;
  56. vis[r]=T;
  57. if (cp[p[r]]!=1) cp[r]=cp[p[r]];
  58. else if (ch[dep[r]]>c[r]) cp[r]=0;
  59. else if (ch[dep[r]]==c[r]) cp[r]=1; else cp[r]=2;
  60. ret+=(cp[r]==0)||(cp[r]==1&&dep[r]<dep[v]);
  61. }
  62. }
  63. return ret;
  64. }
  65. void solve(int u,int f) {
  66. for (auto v:Q[u]) ret[v.se]=gao(u,v.fi);
  67. int pr=c[u];
  68. for (auto v:e[u]) if (v.fi!=f) {
  69. p[u]=v.fi; c[u]=v.se;
  70. solve(v.fi,u);
  71. }
  72. c[u]=pr; p[u]=f;
  73. }
  74. int main() {
  75. scanf("%d%d",&n,&q);
  76. rep(i,1,n) {
  77. scanf("%d%d%s",&u,&v,s);
  78. e[u].pb(mp(v,s[0])); e[v].pb(mp(u,s[0]));
  79. }
  80. dfs(1,0);
  81. rep(i,0,q) {
  82. scanf("%d%d",&u,&v);
  83. Q[u].pb(mp(v,i));
  84. }
  85. solve(1,0);
  86. rep(i,0,q) printf("%d\n",ret[i]);
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement