========================================================================================================================
#include <iostream> #include <cmath> #include <algorithm> #include <string> #include <deque> #include <cstring> #include <cstdio> #include <vector> #include <set> #include <map> #include <queue> #include <cstdlib> using namespace std; typedef long long LL; const LL INF = 0xffffff; const int maxn = 201315; const LL MOD = 1e9+7; vector<vector<int> >G; int Father[maxn], Deep[maxn], ans[maxn]; int n, m; void Init() { G.clear(); G.resize(n+2); memset(Deep, 0, sizeof(Deep)); memset(ans, 0, sizeof(ans)); memset(Father, 0, sizeof(Father)); } void DFS(int fa,int cur,int deep) { Father[cur] = fa; Deep[cur] = deep; int len = G[cur].size(); for(int i=0; i<len; i++) { int v = G[cur][i]; if(v != fa) { DFS(cur, v, deep+1); } } } void LCA(int a,int b) { if(a == b) { // ans[a] -= 2; return ; } if(Deep[a] > Deep[b]) { ans[a] ++; LCA(Father[a], b); } else { ans[b] ++; LCA(a, Father[b]); } } int main() { int T, cas = 1, a, b; scanf("%d", &T); while(T--) { scanf("%d %d",&n, &m); Init(); for(int i=1; i<=n-1; i++) { scanf("%d %d", &a, &b); G[a].push_back(b); G[b].push_back(a); } DFS(0, 1, 0); for(int i=n; i<=m; i++) { scanf("%d %d",&a, &b); LCA(a, b); } int res = INF; for(int i=2; i<=n; i++) res = min(res, ans[i]); printf("Case #%d: %d\n", cas++, res+1); } return 0; }
原文:http://www.cnblogs.com/chenchengxun/p/4833933.html