// Hacker Cup 2017 // Final Round // Fox Tolls // Jacob Plachta #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; #define LL long long #define LD long double #define PR pair #define Fox(i,n) for (i=0; i=0; i--) #define FoxR1(i,n) for (i=n; i>0; i--) #define FoxRI(i,a,b) for (i=b; i>=a; i--) #define Foxen(i,s) for (i=s.begin(); i!=s.end(); i++) #define Min(a,b) a=min(a,b) #define Max(a,b) a=max(a,b) #define Sz(s) int((s).size()) #define All(s) (s).begin(),(s).end() #define Fill(s,v) memset(s,v,sizeof(s)) #define pb push_back #define mp make_pair #define x first #define y second template T Abs(T x) { return(x<0 ? -x : x); } template T Sqr(T x) { return(x*x); } const int INF = (int)1e9; const LD EPS = 1e-12; const LD PI = acos(-1.0); bool Read(int &x) { char c,r=0,n=0; x=0; for(;;) { c=getchar(); if ((c<0) && (!r)) return(0); if ((c=='-') && (!r)) n=1; else if ((c>='0') && (c<='9')) x=x*10+c-'0',r=1; else if (r) break; } if (n) x=-x; return(1); } #define LIM 500000 #define LIM2 2100000 #define MOD 1000000007 int ind; int L[2][LIM],R[2][LIM],S[2][LIM]; vector con[LIM]; int sz; vector lst[LIM2]; void rec(int z,int i,int p) { int j,k; L[z][i]=ind++; Fox(j,Sz(con[i])) if ((k=con[i][j])!=p) rec(z,k,i); R[z][i]=ind-1; S[z][i]=R[z][i]-L[z][i]; } int Query(int i,int r1,int r2,int a,int b,int v1,int v2) { if ((a<=r1) && (r2<=b)) { return( lower_bound(lst[i].begin(),lst[i].end(),v2+1) - lower_bound(lst[i].begin(),lst[i].end(),v1) ); } i<<=1; int m=(r1+r2)>>1,s=0; if (a<=m) s+=Query(i,r1,m,a,b,v1,v2); if (b>m) s+=Query(i+1,m+1,r2,a,b,v1,v2); return(s); } int main() { // vars int T,t; int N,M; int i,j,k,a,b,z,z1,z2; int ans,tot; char c1,c2; // testcase loop Read(T); Fox1(t,T) { // input Read(N),Read(M); Fox(z,2) { // clear graph Fox(i,N) con[i].clear(); // input tree Fox(i,N-1) { Read(j),Read(k),j--,k--; con[j].pb(k); con[k].pb(j); } // calculate DFS ordering for this tree ind=0; rec(z,0,0); } // construct segment tree for(sz=1;szL[z][j]) swap(i,j); // nested subtrees? if (L[z][j]<=R[z][i]) { ans=2*S[z][i] + S[z][j]; goto Done; } // disjoint subtrees ans=2*(S[z][i] + S[z][j]); goto Done; } // different trees if (z1) swap(i,j); ans=2*(S[0][i] + S[1][j]); if ((S[0][i]) && (S[1][j])) ans-=Query(1,0,sz-1,L[0][i]+1,R[0][i],L[1][j]+1,R[1][j]); // update total Done:; tot=((LL)tot*12345+ans)%MOD; } //output printf("Case #%d: %d\n",t,tot); } return(0); }