1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
| #include<bits/stdc++.h> using namespace std;
#define endl '\n' #define debug(a) cout<<#a<<"="<<a<<endl; #define int long long #define x1 x111111 #define y1 y111111 #define x0 x00000 #define y0 y00000
typedef long long ll; typedef pair<int,int> pii;
const double eps=1e-8;
bool multi=1; int n,m; vector<vector<int>> edge;
int exgcd(int a,int b,int &x,int &y){ if(!b){ x=1,y=0; return a; } int d=exgcd(b,a%b,y,x); y-=a/b*x; return d; }
int check(int a1,int b1,int a2,int b2){ int a=b1,b=-b2,c=a2-a1,x0,y0; int d=__gcd(a,b); if(c%d!=0) return 1e9; exgcd(a,b,x0,y0); int x1=x0*c/d,y1=y0*c/d; int ta=abs(b/d); int tb=abs(a/d); int xp=(x1%ta+ta)%ta; return a1+b1*xp; }
int query(int sa,int ta,int sb,int tb){ vector<int> disa(n+1),disb(n+1),from(n+1); vector<bool> sta(n+1),stb(n+1);
auto bfs=[&](int start,int end,vector<int>&dis,vector<int>&from){ queue<int> q; q.push(start); while(q.size()){ int u=q.front(); q.pop(); for(auto v:edge[u]){ if(v==from[u]) continue; from[v]=u; dis[v]=dis[u]+1; q.push(v); if(v==end){ while(q.size()) q.pop(); break; } } } };
bfs(sa,ta,disa,from);
vector<int> patha; int cur=ta; while(1){ sta[cur]=true; patha.push_back(cur); if(cur==sa) break; cur=from[cur]; }
for(int i=1;i<=n;i++) from[i]=0; bfs(sb,tb,disb,from);
cur=tb; while(1){ stb[cur]=true; if(cur==sb) break; cur=from[cur]; }
int dza=disa[ta],dzb=disb[tb]; int res=1e9,ver; for(auto i:patha){ if(!stb[i]) continue; int da=disa[i],db=disb[i]; int a1=da,b1=2*dza,a2=2*dza-da,b2=b1; int a3=db,b3=2*dzb,a4=2*dzb-db,b4=b3; int val=min({check(a1,b1,a3,b3),check(a1,b1,a4,b4),check(a2,b2,a3,b3),check(a2,b2,a4,b4)}); if(res>val){ res=val; ver=i; } } if(res==1e9){ return -1; }else{ return ver; } }
void solve(){ cin>>n>>m; edge.clear(); edge.resize(n+1); for(int i=1;i<n;i++){ int u,v; cin>>u>>v; edge[u].push_back(v); edge[v].push_back(u); } while(m--){ int sa,ta,sb,tb; cin>>sa>>ta>>sb>>tb; cout<<query(sa,ta,sb,tb)<<endl; } }
signed main(){ ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); int TTT=1; if(multi) cin>>TTT; while(TTT--){ solve(); }
return 0; }
|