fork(1) download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4.  
  5. int main()
  6. {
  7. int t; cin>>t;
  8. while(t--)
  9. {
  10. int n; cin>>n;
  11. string s; cin>>s;
  12. vector<int>leaf;
  13. int mp[n+1];
  14. memset(mp,0,sizeof(mp));
  15. vector<int>par(n+2);
  16. par[1]=-1;
  17. for(int i=0;i<n;i++){
  18. int x,y; cin>>x>>y;
  19. if(x==0 && y==0){
  20. leaf.push_back(i+1);
  21. }else{
  22. mp[x]=0;
  23. mp[y]=1;
  24. par[x]=i+1;
  25. par[y]=i+1;
  26. }
  27. }
  28. int cnt=0;
  29. int ans=INT_MAX;
  30. int itr=0;
  31. for(auto x: leaf){
  32.  
  33. int u=x;
  34. cnt=0;
  35. while(u!=-1 ){
  36.  
  37. int left=0, right=0;
  38. if(mp[u]==0)left=1;
  39. else right=1;
  40. u=par[u];
  41. if(left && s[u-1]!='L')cnt++;
  42. else if(right && s[u-1]!='R')cnt++;
  43. else if(s[u-1]=='U')cnt++;
  44. if(cnt-1>=ans)break;
  45.  
  46.  
  47. }
  48. ans=min(ans, cnt-1);
  49.  
  50. }
  51.  
  52. cout<<ans<<endl;
  53.  
  54. }
  55. }
Runtime error #stdin #stdout 0.81s 2095876KB
stdin
Standard input is empty
stdout
Standard output is empty